如何进行跨域配置
nginx跨域配置
location / {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
}
location / {
add_header "Access-Control-Allow-Origin" *;
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS";
add_header "Access-Control-Allow-Headers" "Authorization";
}
配置参考3,只支持某个来源的域名跨域
location / {
add_header "Access-Control-Allow-Origin" 'vivo.com.cn';
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS";
add_header "Access-Control-Allow-Headers" "Authorization";
}
注意点
nginx如果配置了跨域配置,则后端服务无需配置改配置。如果有多层nginx,则只需要有一层nginx配置了该配置即可。同理,如果服务端(flask/django等)配置了跨域,则nginx无需此配置。
否则会出现以下错误:The 'Access-Control-Allow- Origin' header contains multiple values '*, *', but only one is allowed
http://api-ai.vivo.com.cn/bosum/homeworkFilter Default levels 1ss
Access to XMLHttpRequest at 'http://api-ai.vivo.com.cn/bosum/homework correct'from origin 'http://localhost:9532' has been blocked by CORS p 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. POST http://api-ai.vivo.com.cn/bosum/homework correct net::ERR_FAILED
flask跨域配置
配置全局跨域配置或者单个路由支持跨域:https://blog.csdn.net/qq_38161040/article/details/123994884
测试工具
如何测试自己的接口是否支持跨域
1.在线测试网站:https://cors-test.codehappy.dev
2.浏览器测试方法:https://developer.aliyun.com/article/688172
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.xxx.com/api/action');
xhr.send(null);
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}
3.curl命令测试响应头是否是否支持跨域:https://tecadmin.net/how-to-enable-cors-in-nginx/
curl -v http://your_domain.com