上一章我们有讲过关于CORS协议的跨域协议头,接下来我们从php,nginx,apache三个方面来讲一下分别如何配置跨域
PHP代码中配置
//服务端代码
//json头
header("Content-type: application/json");
//跨域CORS
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: 跨域URL");
header("Access-Control-Request-Methods:GET, POST, PUT, DELETE, OPTIONS");
header('Access-Control-Allow-Headers:x-requested-with,content-type,ch-token');
//JS请求代码
$.ajax({
type: "POST",
url: "",
xhrFields: {withCredentials: true},
crossDomain: true,
data: "",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("ch-token", 'chris');
},
error: function (XMLHttpRequest) {
if (XMLHttpRequest.status === 401) {
}
},
success: function () {},
complete: function () {}
});
Nginx 配置跨域
#1.可以添加协议头
server
{
listen 8080;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
}
#2.可以利用反向代理实现跨域,建议
location /api{ //通过api路径请求的
rewrite ^/api/?(.*)$ /$1 break; //重写
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://192.168.137.189:8082/; # 转发地址
}
Apache 跨域配置
1.首先找到 httpd.conf 文件
找到 #LoadModule headers_module modules/mod_headers.so
把#注释符去掉(也有可能已经默认去掉了)
目的是开启apache头信息自定义模块
2.
<Directory "E:/laragon/www/(你的本地地址)">
AllowOverride All
Require all granted
Header set Access-Control-Allow-Origin * //添加
</Directory>