報錯1信息
Access to XMLHttpRequest at 'http://localhost:4445/api/v/getmsg' from origin 'http://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
解決方案
參考資料:https://segmentfault.com/q/1010000016765176,把value值改成特定的域名。
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:9528" />
</httpProtocol>
</system.webServer>
報錯2信息
Access to XMLHttpRequest at 'http://localhost:4445/api/v/getmsg' from origin 'http://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
解決方案
增加一行配置文件
<add name="Access-Control-Allow-Credentials" value="true" />
報錯3信息
Access to XMLHttpRequest at 'http://localhost:4445/api/v/getmsg' from origin 'http://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
原因
瀏覽器請求接口時會發送兩個請求,一個是預請求,相當於確認請求,第二個請求才是你要發送的真正的請求,而這個錯誤信息說明的是第一個OPTINOS請求失敗,在服務端沒有處理這個method為OPTIONS的請求,需要對它處理一下:
解決方案:
參考資料:關於Web API 2.0中的Options請求返回405的問題
public class SpecialMethodModule : IHttpModule { public SpecialMethodModule() { } public void Init(HttpApplication app) { app.BeginRequest += new EventHandler(this.BeginRequest); } public void Dispose() { } public void BeginRequest(object resource, EventArgs e) { HttpApplication app = resource as HttpApplication; HttpContext context = app.Context; if (context.Request.HttpMethod.ToUpper() == "OPTIONS") { context.Response.StatusCode = 200; context.Response.End(); } } }
在web.config中增加module節點,參考微軟官方文檔,根據IIS版本不同,增加的節點方式也不同,我是IIS10.0
<configuration>
<system.webServer>
<modules>
<add name="HelloWorldModule" type="HelloWorldModule"/>
</modules>
</system.webServer>
</configuration>
這是我遇到的問題,進行解決以及整理,有其他問題歡迎溝通。
