nginx跨域问题
简单说,跨域分为简单跨域和复杂跨域。
简单跨域不会发送OPTIONS请求。
复杂跨域会发送一个预检查OPTIONS请求。
复杂跨域的条件是:
- 非GET、HEAD、POST请求。
- POST请求的
Content-Type不是application/x-www-form-urlencoded,multipart/form-data, 或text/plain。 - 添加了自定义header,例如
Token。
报错信息

nginx配置
location / {
if ($request_method = 'OPTIONS') {
#add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,authorization';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
#add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,authorization';
proxy_pass http://xxxxx;
}

浙公网安备 33010602011771号