header('Access-Control-Allow-Origin:*');不允许CORS请求

时间:2013-11-25 10:27:20

标签: php cors

我有一个生成JSON文档的PHP文件。

我已将header设置如下,但仍然出错。

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

错误讯息:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://mysubdomain.mydomain.com' is therefore not allowed access.

我已尝试使用

明确允许mysubdomain.mydomain.com
header('Access-Control-Allow-Origin: https://mysubdomain.mydomain.com');

但我仍然得到错误。

3 个答案:

答案 0 :(得分:6)

看起来设置标头的代码没有任何问题,但您可能想要检查标头是否实际设置。使用curl -i http://yourapp检查发送的响应标头以进行调试。或者,您可以使用Google Chrome网络检查器中的网络标签,或Firefox的Web开发人员工具中的网络工具。

答案 1 :(得分:1)

当请求的页面上发生错误时,可能会出现这种情况。在这种情况下,错误页面设置标头,可能没有Access-Control-Allow-Origin标头。

答案 2 :(得分:0)

使用htaccess文件,您可以尝试设置:

Header always set Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, PATCH,DELETE"
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Allow-Headers "content-type,Authorization,Cache-Control,X-Requested-With, X-XSRF-TOKEN"

或者可以将php用于:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, PATCH, DELETE');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Authorization, Content-Type, x-xsrf-token, x_csrftoken, Cache-Control, X-Requested-With');