javascript - CORS、IIS7 和 PHP - Access-Control-Allow-Origin 错误

标签 javascript php iis-7 xmlhttprequest cors

我正在尝试允许另一台主机(本地主机,如 javascript.dev)为该主机创建一个 xhr,它是一个 IIS7,如果我 curl -I 它,这是 header :

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 的 header :

* 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" />

最佳答案

根据评论,您似乎在提交 OPTIONS 请求时缺少 Access-Control-Allow-Origin header 。根据this article 它应该是将以下代码添加到您的 PHP 页面的简单案例...

<?php
header('Access-Control-Allow-Origin: *');
?>

如果仍然不起作用,那么您应该检查 PHP 的 IIS 处理程序映射(参见 here )并确保 OPTIONS 是一个允许的动词。希望这能完成工作!

This文章还指出您可以完全跳过修改 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>

请注意,这将打开整个网站,而不仅仅是一个页面...

关于javascript - CORS、IIS7 和 PHP - Access-Control-Allow-Origin 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24327106/

相关文章:

javascript - Typescript 扩展第三方声明文件

javascript - 更改前清理输入

javascript - 如何处理 ngFor 中输入类型的动态正则表达式值?

php - php/html 中的动态复选框

c# - ASP.Net "Access to the path ' ' 被拒绝。“文件上传控件在 Web 服务器 (IIS7) 中不起作用

iis-7 - IIS7 Windows 2008 服务器上的经典 ASP 模拟问题

javascript - 执行 JavaScript 代码的尴尬方式

php - 为什么我不应该在 PHP 中使用 mysql_* 函数?

php - 无法从单独的文件中检索数据库连接信息

c# - 创建短网址服务时,302 临时重定向是最好的方法吗?