Nginx 支持 CORS
先说下最终增加的配置:
add_header Access-Control-Allow-Origin https://a.domain.com always;
add_header Access-Control-Allow-Headers 'content-type,authorization';
add_header Access-Control-Max-Age 3600;
if ($request_method = 'OPTIONS') {
return 204;
}
Web 项目(a.domain.com
)和后端接口(b.domain.com
)调试时遇到:
Access to XMLHttpRequest at 'https://b.domain.com/v1/auth/login' from origin 'https://a.domain.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
在接口 b.domain.com
的 Nginx 配置中增加,(需要加上 always
否则没什么效果):
# add_header Access-Control-Allow-Origin https://a.domain.com;
add_header Access-Control-Allow-Origin https://a.domain.com always;
增加配置信息后,错误信息变成了:
Access to XMLHttpRequest at 'https://b.domain.com/v1/auth/login' from origin 'https://a.domain.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
因为跨域的时候,会先发请一个 OPTIONS
的预检请求,这个请求响应成功之后才会发送实际的请求,所以对于这个请求要给出正确的响应:
if ($request_method = 'OPTIONS') {
return 204;
}
增加配置后,错误信息变成了:
Access to XMLHttpRequest at 'https://b.domain.com/v1/auth/login' from origin 'https://a.domain.com' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
增加配置信息:
add_header Access-Control-Allow-Headers 'content-type,authorization';
现在可以正常发送跨域的请求了。
不过,每个请求发送前,都会对应发送一个预检请求,再调整下配置:
add_header Access-Control-Max-Age 3600;
增加这个配置,告知客户端允许的请求头可以缓存多久,在缓存有效期内不再发送预检请求。
参考文章:
标签:Control,domain,header,支持,Access,Nginx,https,CORS,com From: https://www.cnblogs.com/zhpj/p/18199686/nginx-support-cos-z2aakcg