header('Access-Control-Allow-Origin: *'); Not allowing CORS request

六眼飞鱼酱① 提交于 2021-02-06 09:10:15

问题


I have a PHP file which generates a JSON document.

I've set the header as follows but am still getting an error.

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

Error message:

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

I've tried explictly allowing mysubdomain.mydomain.com using

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

But I still get the error.


回答1:


It doesn't look there is anything wrong with the code that sets the header, but you may want to check if the header is actually being set. Use curl -i http://yourapp to check the response headers being sent to debug it. Alternatively, you can use the network tab in Google Chrome's web inspector, or the Network tool in Firefox's Web Developer tools.




回答2:


Such a situation may arise when an error occurs on the requested page. In this case the error page sets headers, that likely has no Access-Control-Allow-Origin header.




回答3:


with htaccess file you can try to set :

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"

or can use for php as:

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');


来源:https://stackoverflow.com/questions/20189756/headeraccess-control-allow-origin-not-allowing-cors-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!