![](/img/trans.png)
[英]AWS - has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
[英]CORS error - No 'Access-Control-Allow-Origin' header is present on the requested resource
我正在使用Angular前端连接到WEB API 2后端。 失败的用例如下。 用户注册后,成功注册后,必须将他们登录到系统中并重定向到新页面以收集更多信息。 我正在使用令牌进行身份验证。
我已经在WebAPI配置中启用了CORS:
var cors = new EnableCorsAttribute("http://localhost:7812", "*", "*");
config.EnableCors(cors);
注册请求成功,并且响应标头具有必需的CORS标头:
**Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:7812**
Content-Length:0
Date:Sun, 24 Aug 2014 09:31:55 GMT
Server:Microsoft-IIS/8.0
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcUHJvamVjdHNcVGVzdGluZ1xNYWx0QXBhcnRtZW50c1xNYWx0YXBhcnRtZW50cy5BUElcTWFsdGFwYXJ0bWVudHMuQVBJXGFwaVxhY2NvdW50XHJlZ2lzdGVy?=
在下一步中,我尝试将用户登录到系统。 作为登录的一部分,前端通过Request URL:http://localhost:7802/token
向服务器Request URL:http://localhost:7802/token
。 请求标头再次发送一个Origin标头Origin:http://localhost:7812
但是这次我收到错误消息: XMLHttpRequest cannot load http://localhost:7802/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:7812' is therefore not allowed access.
XMLHttpRequest cannot load http://localhost:7802/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:7812' is therefore not allowed access.
有人有想法么?
在处理CORS时,我们需要记住,对于非GET请求,浏览器可能会发送两个请求。 通常会有一个预检(OPTIONS)请求,然后是实际的请求(POST)。 在预检请求期间,服务器需要添加Access-Control-Allow-Origin标头,其值与请求的Origin标头匹配。 这授权随后的请求被发送。
对于后续/实际请求,服务器还需要添加Access-Control-Allow-Origin标头。 否则,该请求将失败。
使用OWIN OAuthAuthorizationServerProvider时,我们需要自定义MatchEndpoint处理程序以管理标头逻辑。 在验证客户端身份验证之前执行此处理程序。
有关更多背景信息,请查看以下链接: http : //www.ozkary.com/2016/04/web-api-owin-cors-handling-no-access.html
我相信您有两个问题:
1-使用Web API 2,您在授予不记名令牌时需要手动添加标头。
2-您的数据需要进行url编码,因此您需要拦截$ http post消息以对数据进行编码。
请参阅我从AngularJS客户端使用Web API 2的文章。
http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En
希望能有所帮助。
在web.config中使用以下行:
<system.webServer>
<modules>
<remove name="WebDAVModule" />
...
</modules>
<handlers>
<remove name="WebDAV" />
...
</handlers>
</system.webServer>
它解决了我的问题,可能还可以帮助您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.