Я использую nodejs на сайтах Azure. Я установил пакет cors и включил запросы от всех доменов. Azure все еще блокировал запрос CORS.
Я изменил web.config (на каждом сайте есть один, если он не является частью развертывания, затем он создается). За этой StackOverflow должность: HTTP OPTIONS request on Azure Websites fails due to CORS
Моей полной web.config ниже - Есть настройки специфичны для моего сайта, поэтому копирование и вставка не будет работать.
<?xml version="1.0" encoding="utf-8"?>
<!--
This configuration file is required if iisnode is used to run node processes behind
IIS or IIS Express. For more information, visit:
https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config
-->
<configuration>
<system.webServer>
<!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support -->
<webSocket enabled="false" />
<handlers>
<!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
<add name="iisnode" path="transpiled/www.js" verb="*" modules="iisnode"/>
</handlers>
<rewrite>
<rules>
<!-- Do not interfere with requests for node-inspector debugging -->
<rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
<match url="^transpiled/www.js\/debug[\/]?" />
</rule>
<!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
<rule name="StaticContent">
<action type="Rewrite" url="public{REQUEST_URI}"/>
</rule>
<!-- All other URLs are mapped to the node.js site entry point -->
<rule name="DynamicContent">
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
</conditions>
<action type="Rewrite" url="transpiled/www.js"/>
</rule>
</rules>
</rewrite>
<!-- 'bin' directory has no special meaning in node.js and apps can be placed in it -->
<security>
<requestFiltering>
<hiddenSegments>
<remove segment="bin"/>
</hiddenSegments>
</requestFiltering>
</security>
<!-- Make sure error responses are left untouched -->
<httpErrors existingResponse="PassThrough" />
<!--
You can control how Node is hosted within IIS using the following options:
* watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
* node_env: will be propagated to node as NODE_ENV environment variable
* debuggingEnabled - controls whether the built-in debugger is enabled
See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options
-->
<!--<iisnode watchedFiles="web.config;*.js"/>-->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,DELETE,HEAD,PUT,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Olaround-Debug-Mode, Authorization, Accept" />
<add name="Access-Control-Expose-Headers" value="X-Olaround-Debug-Mode, X-Olaround-Request-Start-Timestamp, X-Olaround-Request-End-Timestamp, X-Olaround-Request-Time, X-Olaround-Request-Method, X-Olaround-Request-Result, X-Olaround-Request-Endpoint" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
Скопируйте этот раздел и вставить его прямо над закрытия system.webServer тега.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,DELETE,HEAD,PUT,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Olaround-Debug-Mode, Authorization, Accept" />
<add name="Access-Control-Expose-Headers" value="X-Olaround-Debug-Mode, X-Olaround-Request-Start-Timestamp, X-Olaround-Request-End-Timestamp, X-Olaround-Request-Time, X-Olaround-Request-Method, X-Olaround-Request-Result, X-Olaround-Request-Endpoint" />
</customHeaders>
</httpProtocol>
Чтобы получить web.config, вам придется развернуть, а затем FTP в экземпляр. Вы можете сделать это, нажав ссылку «Загрузить ссылку публикации» на панели инструментов сайта.
Открыть файл вверх, это xml.
<?xml version="1.0"?>
<publishData>
<publishProfile profileName="secret - Web Deploy" publishMethod="MSDeploy" publishUrl="secret.scm.azurewebsites.net:443" msdeploySite="secret" userName="$secret" userPWD="v0ifRuLpeXf42kurCFHqXSA5uQnAdmx2c7lCHrrQPiyB6TxlXoG0dfJGFndH" destinationAppUrl="http://secret.azurewebsites.net" SQLServerDBConnectionString="" mySQLDBConnectionString="" hostingProviderForumLink="" controlPanelLink="" webSystem="WebSites">
<databases/>
</publishProfile>
<publishProfile profileName="secret - FTP" publishMethod="FTP" publishUrl="ftp://secret.ftp.azurewebsites.windows.net/site/wwwroot" ftpPassiveMode="True" userName="secret\$secret" userPWD="secret2c7lCHrrQPiyB6TxlXosecret" destinationAppUrl="http://secret.azurewebsites.net" SQLServerDBConnectionString="" mySQLDBConnectionString="" hostingProviderForumLink="" controlPanelLink="" webSystem="WebSites">
<databases/>
</publishProfile>
</publishData>
В элементе publishProfile для FTP вы найдете URL-адрес, имя пользователя и пароль. Используйте значения целиком, иначе это не сработает.
Как только у вас есть web.config, внесите изменения и загрузите его обратно на сайт. Посмотрите, работает ли это. Это было для меня.
Чтобы он продолжал работать, вам нужно добавить web.config в корень проекта (или сайта). В противном случае Azure ударит его при каждом развертывании.
Вы пробовали посмотреть этот пост? http://stackoverflow.com/questions/18981339/http-options-request-on-azure-websites-fails-due-to-cors. Он использует PHP, но изменение заголовков в файле web.config должно иметь тот же эффект. –