一、nginx配置跨域
location / {
# 配置允许跨域的域名
add_header Access-Control-Allow-Origin *;
# 为 true 的时候指请求时可带上Cookie
# add_header 'Access-Control-Allow-Credentials' 'true';
# 配置允许的方法
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
# 允许请求头自定义的参数名称
add_header Access-Control-Allow-Headers 'Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}
二、部分错误
2.1 重复配置跨域错误
The 'Access-Control-Allow-Origin' header contains multiple values'*, *', but only one is allowed
解决方案:检查是否nginx配置了跨域,代码中是否也设置了跨域。
2.2 配置冲突导致跨域失败
Response to preflight request doesn't pass access control check:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'
这个错误就是一般因为前端有以下配置:
axios.defaults.withCredentials= true
ngnix或者后端设置跨域设置了Access-Control-Allow-Origin 的值为 '*'。可以修改后端:
res.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
res.addHeader("Access-Control-Allow-Credentials","true");