浏览器同源策略:
- 同一个协议
- 同一个端口
- 同一个域名
不满足同源策略,浏览器就视为是跨域请求 **
处理方式有两种
- nginx
- web server
nginx:
```nginx location / {proxy_set_header Host $host:$server_port;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header Access-Control-Allow-Origin "$http_origin";
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
add_header Cache-Control no-cache;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
proxy_pass 代理地址
}
或只给 `options` 请求加速
```nginx
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, DELETE";
add_header Access-Control-Max-Age "3600";
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization";
add_header Content-Type text/plain;
add_header 'Access-Control-Allow-Credentials' 'true';
return 200;
}
web server:
- 返回增加相关cors插件
- 一般
Access-Control-Allow-Credentials
为true
时,必须要前端header
传递origin
参数,值为当前前端域名 ,并且Access-Control-Allow-Origin
不能为*
。