我试图允许其他主机(本地主机,如javascript.dev
)向该主机发送xhr,它是一个IIS7,如果我curl -I
它,这是头:
HTTP/1.1 200 OK
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Server: Microsoft-IIS/7.0
X-Powered-By: PHP/5.3.28
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS
Access-Control-Max-Age: 1000
Access-Control-Allow-Headers: *
X-Powered-By: ASP.NET
Date: Fri, 20 Jun 2014 12:09:33 GMT
这是curl -v -X OPTIONS
的标题:
* About to connect() to www2.xxxxxxxxxxxx.com.br port 80 (#0)
* Trying 200.98.xxx.100...
* Connected to www2.xxxxxxxxxxxx.com.br (200.98.xxx.100) port 80 (#0)
> OPTIONS /jobs/xxxxxxx/user/ HTTP/1.1
> User-Agent: curl/7.30.0
> Host: www2.xxxxxxxxxxxx.com.br
> Accept: */*
>
< HTTP/1.1 200 OK
< Allow: OPTIONS, TRACE, GET, HEAD, POST
* Server Microsoft-IIS/7.0 is not blacklisted
< Server: Microsoft-IIS/7.0
< Public: OPTIONS, TRACE, GET, HEAD, POST
< X-Powered-By: ASP.NET
< Date: Fri, 20 Jun 2014 13:01:25 GMT
< Content-Length: 0
我使用php来更改Access-Control-Allow-Origin
,但是当我使用xhr时,无论是否有jquery,这都是我得到的错误:
XMLHttpRequest cannot load http://www2.xxxxxxxx.com.br/jobs/xxxxxx/user/.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://javascript.dev' is therefore not allowed access.
要记录,我要解决的其他步骤:
我将上面的答案中的代码添加到我的web.config中并收到此错误:
XMLHttpRequest cannot load http://www2.madeinweb.com.br/jobs/eminhasaude/user.
Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
因为Access-Control-Allow-Headers
不接受通配符*
。解决:
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
答案 0 :(得分:5)
根据评论,在提交OPTIONS请求时,您似乎错过了Access-Control-Allow-Origin
标头。根据{{3}}文章,它应该是一个简单的例子,将以下代码添加到PHP页面......
<?php
header('Access-Control-Allow-Origin: *');
?>
如果仍然无效,那么您应该检查PHP的IIS处理程序映射(请参阅this)并确保OPTIONS是允许的动词。希望能做到这一点!
here文章还表明您可以完全跳过修改PHP,只需将以下内容添加到您的web.config中:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
<add name="Access-Control-Max-Age" value="1000" />
</customHeaders>
</httpProtocol>
</system.webServer>
请注意,这将打开整个网站,而不仅仅是一个页面......