描述:在处理跨域问题时,使用nginx绕开跨域问题
$.ajax({
type: "POST",
url: "http://www.wqlblog.cn/write",
dataType: "json",
contentType: "application/json; charset=utf-8",
//············
}
在postman中,发送post请求正常,而在浏览器中发送post请求报错,查看信息为
Access to XMLHttpRequest at ‘xxx’ from origin ‘xxx’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
原因:浏览器发送post请求会事先发送一次预检请求(OPTIONS请求),而postman等测试软件并不会发送该请求,因此浏览器报错而postman软件不报错
触发预检请求的三类条件:
- 默认情况下,跨域请求只支持GET,HEAD,POST方法,如果不是这三个请求方法(比如:PUT、DELETE、CONNECT、OPTIONS、TRACE和PATCH),那么将触发预检请求
- 默认情况下,浏览器跨域请求时,会自动添加的请求头(HOST,Referer,Connection、Accept、User-Agent,Accept-Languange,Accept-Encoding,Accept-Charset和Content-Type),这些请求中还有其他请求头时,那么将触发预检请求。
- 如1、2所说的情况排除在外的条件下,跨域请求是,浏览器支持的Content-Type值为application/x-www-form-urlencoded,multipart/form-data和text/plain。如果是其他数据类型(如application/json,text/xml…),那么将触发预检请求。
解决办法
nginx中location中插入如下代码以回应预检请求
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Max-Age 1728000;
add_header Access-Control-Allow-Methods 'GET,POST,OPTIONS,PUT,DELETE'; add_header Access-Control-Allow-Headers 'Token,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,ACCESS-TOKEN,x-file-name,Cookie';
add_header Content-Type 'application/json;application/x-www-form-urlencoded;text/plain; charset=utf-8';
add_header Content-Length 0 ;
add_header Access-Control-Allow-Credentials true;
return 204;
}