允许指定的域名,方法,请求头访问
header("Access-Control-Allow-Origin: http://example.com");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
允许所有域名,方法,头访问
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: *");
header("Access-Control-Allow-Headers: *");
JSONP解决方案
//前端文件
function callback(data) {
console.log(data);
}
var script = document.createElement('script');
script.src = 'http://example.com/api?callback=callback';
document.body.appendChild(script);
//后端文件
$data = array('name' => 'John', 'age' => 25);
$jsonpData = json_encode($data);
$callback = $_GET['callback'];
echo $callback . '(' . $jsonpData . ')';
NGINX 解决跨域
location ~ \.php/?.*$ {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PATCH, DELETE, PUT, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Access-Control-Expose-Headers, Token, Authorization';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
}