CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。
它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
NGINX端:
location / {
...
add_header ‘Access-Control-Allow-Origin‘ *;
add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, OPTIONS‘;
add_header ‘Access-Control-Allow-Headers‘ ‘Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin,Range‘;
add_header ‘Access-Control-Expose-Headers‘ ‘Content-Length,Content-Range‘;
...
}
或者 在 PHP代码中设定 (php代码中设置了, nginx就不要配置了, 二选一):
header(‘Access-Control-Allow-Origin:*‘); // 设为星号,表示同意任意跨源请求。也可配置特定的域名可访问 如: https://www.xxxx.com
header(‘Access-Control-Allow-Methods:OPTIONS,POST,GET‘); // 允许请求的类型
header(‘Access-Control-Allow-Headers:Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin‘);