CORS on Apache php

Leaves and dew

错误

Access-Control-Allow-Origin

1
2
Access to XMLHttpRequest at 'http://bookmarks.x0ox.xyz/api/qrcode.php' popup.js:27 
from origin 'chrome-extension://mfhbgdlbkinkfilcddigcdcidecnefbi' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

问题原因

​ 跨域请求

解决

php文件添加header,注意:添加后意味着全部站都可以跨域请求。

1
2
3
4
5
header('Access-Control-Allow-Origin:*');#所有域名都可以

header('Access-Control-Allow-Origin:https://nobige.cn');#单个域名

header('Access-Control-Allow-Origin:'.['https://nobige.cn','https://www.nobige.cn']);#多个域名

或者.htaccess文件添加

1
2
3
Header set Access-Control-Allow-Origin "*"#所有域名都可以

Header set Access-Control-Allow-Origin "https://nobige.cn";#单个域名

注意:.htaccess不支持多个域名,要么单个域名,要么全部域名

注意:.htaccess不支持多个域名,要么单个域名,要么全部域名

注意:.htaccess不支持多个域名,要么单个域名,要么全部域名

同理在httpd.conf添加对于的代码也是可行的

<Directory>, <Location>, <Files> 或者 <VirtualHost>字段内添加

1
2
3
Header set Access-Control-Allow-Origin "*"#所有域名都可以

Header set Access-Control-Allow-Origin "https://nobige.cn";#单个域名

和.htaccess一样,不支持多个域名,要么单个域名,要么全部域名

注意:如果在php中添加,.htaccess文件或者httpd.conf文件中不能有相同功能的代码,否者会冲突

Access-Control-Allow-Origin

1
Access to XMLHttpRequest at 'http://bookmarks.x0ox.xyz/api/import.php' from origin 'chrome-extension://mfhbgdlbkinkfilcddigcdcidecnefbi' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.

其他错误

Access-Control-Allow-Headers

1
Access to XMLHttpRequest at 'http://bookmarks.x0ox.xyz/api/import.php' from origin 'chrome-extension://mfhbgdlbkinkfilcddigcdcidecnefbi' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

也可以添加对于header

1
header('Access-Control-Allow-Headers:*');

参考