我最近遇到了将Javascript请求发布到另一个域的问题.默认情况下,不允许将XHR发布到其他域.
按照http://enable-cors.org/的说明,我在其他域上启用了此功能.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

现在一切正常,但是在发回工作200响应之前仍然会返回405响应.
Request URL:http://testapi.nottherealsite.com/api/Reporting/RunReport
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Access-Control-Request-Headers:origin, content-type, accept
Access-Control-Request-Method:POST
Connection:keep-alive
Host:testapi.nottherealsite.com
Origin:http://test.nottherealsite.com
Referer:http://test.nottherealsite.com/Reporting
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1
Response Headersview source
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Origin:*
Allow:POST
Cache-Control:private
Content-Length:1565
Content-Type:text/html; charset=utf-8
Date:Tue, 18 Sep 2012 14:26:06 GMT …Run Code Online (Sandbox Code Playgroud) 我正在尝试从AngularJS页面连接到ASP.NET Web-API Web服务,我得到以下内容
凭据标志为"true",但"Access-Control-Allow-Credentials"标头为"".允许凭据必须为"true".原产地" 的http://本地主机:221 "因此不允许访问.
var cors = new EnableCorsAttribute("http://localhost:221", "*","GET,PUT,POST,DELETE");
config.EnableCors(cors);
Run Code Online (Sandbox Code Playgroud)
使用此AngularJS
$http({
method: 'GET',
url: 'http://localhost:1980/api/investors/62632',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
withCredentials: true
// withCredentials: true,
}).then(function onUserComplete(response) {
// this callback will be called asynchronously
// when the response is available
}, function onError(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
Run Code Online (Sandbox Code Playgroud)
阅读了很多文章后,我将其添加到web.config中
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:221" />
</customHeaders>
</httpProtocol>
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息
'Access-Control-Allow-Origin'标头包含多个值localhost:221,localhost:221,但只允许一个.原因localhost:221因此不允许访问.
这真的没有任何意义,因为我已经添加了一次,它没有找到它,但我将它添加到web.config并得到一个错误说它被添加了多次.我看了很多文章,似乎找不到合适的答案.我正在使用Google Chrome.非常感谢你的帮助,因为我现在正在拔头发.