![](/img/trans.png)
[英]Access to XMLHttpRequest from origin 'http://localhost:4200' has been blocked by CORS policy (Angular, WebApi)
[英]How can I fix access to script blocked by CORS when redirecting from http to https with Angular?
我有一個內置 Angular 8.2 的 SPA,運行在 IIS 10 上。
使用 URL 重寫模塊,我創建了一個規則,將站點從 http 重定向到 https
下面是 web.config 的相關部分和 Angular SPA 重寫規則:
<rule name="Angular" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
<rule name="HTTPS Redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
</rule>
當我使用 http://eqht-dev 訪問根站點時,它會正確重定向到 https://eqht-dev。
但是,如果我直接使用 http://eqht-dev/search 導航到子模塊,我不會被重定向到 https://eqht-dev/search。 相反,我收到 CORS 錯誤:
Access to script at 'https://eqht-dev/runtime-es2015.58df40519ca9af120208.js' (redirected from 'http://eqht-dev/runtime-es2015.58df40519ca9af120208.js') from origin 'http://eqht-dev' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我試圖將 CORS 模塊添加到 web.config:
<cors enabled="true" failUnlistedOrigins="true">
<add origin="http://eqht-dev" allowCredentials="true"/>
</cors>
但是在嘗試訪問主頁時出現 403:
GET https://eqht-dev/runtime-es2015.58df40519ca9af120208.js net::ERR_ABORTED 403
如何正確地將調用 http 的調用重定向到相關的 https 子模塊(http://eqht-dev/search 到 https://eqht-dev/search)?
更新 2022.3.10我在下面實施了 @samwu 建議。 雖然這確實允許站點訪問 function,但它仍然可以訪問 http。調用后端 api 會導致額外的 CORS 錯誤,因為后端僅允許來自 https 的調用。
這是由於子模塊的結構類似於查詢字符串嗎? 我將嘗試像這樣添加查詢字符串: https://bobnoordam.nl/windows/iis-redirect-to-https-and-keep-your-query-string/ 。
更新 2:2022.3.10 在這里看起來像這個問題: https://serverfault.com/questions/1046607/angular-and-iis-redirect-to-https-keeping-full-url
但是,我的配置文件與他們的配置文件相匹配,它仍然不是 bueno。
您的 https 重定向沒問題,您應該嘗試解決 CORS 錯誤。 嘗試以下設置以在 iis 中啟用 cors,將其合並到應用程序/站點根目錄下的 web.config 文件中:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
檢查我上面發布的鏈接后: https://serverfault.com/questions/1046607/angular-and-iis-redirect-to-https-keeping-full-url ,我注意到我的重寫規則不在同一順序那是在那篇文章中。
事實證明規則順序很重要。 HTTPS 重定向規則必須在 angular 重命名規則之前。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.