背景
当前流行前后端分离,很多时候前端域名与后端域名不一致,导致请求跨域被浏览器拦截。
浏览器控制台出现以下提示
原理及解决方案
页面发起跨域请求后,浏览器会先发起预检请求,预检通过后,在发起正式请求。如果预检请求不过,浏览器就会停止后面的业务请求,导致访问失败。
解释
- 预检请求-如字面意思,就是在发起真实的业务请求前,先发送一个检测请求,如果服务端允许跨域,会在响应头中添加相应的header,表明自己允许跨域。
- 预检请求不是必须的,请求符合特定特征时,才需要发送预检。具体的可以参考阮一峰老师的博客http://www.ruanyifeng.com/blog/2016/04/cors.html。
- 即使通过了预检请求,服务端对于业务请求的响应也需要添加跨域头,不然还是会被浏览器拦截。
解决方案
跨域拦截是浏览器的行为与服务端无关,浏览器仅仅只是检查服务端的响应中是否包含跨域头,至于这个头是java服务生成的,还是nginx生成的都可以。
我们的组网如上,nginx做负债均衡,因为我们微服务较多,所以在nginx这一层做了配置来支持跨域,避免每个服务都去配置一遍。
if ($request_method = OPTIONS) {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, HEAD, DELETE,TRACE,PUT,CONNECT';
add_header 'Access-Control-Allow-Headers' xx
return 200;
}
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, HEAD, DELETE,TRACE,PUT,CONNECT';
add_header 'Access-Control-Allow-Headers' xx
闭坑指导
上述支持跨域的配置中未给每个配置项配置always,导致服务端返回非200时,跨域头未加上去,浏览器报跨域。
这个坑可以参考nginx的官方文档http://nginx.org/en/docs/http/ngx_http_headers_module.html
Syntax: add_header name value [always];
Default: —
Context: http, server, location, if in location
Adds the specified field to a response header provided that the response code equals 200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), or 308 (1.13.0). Parameter value can contain variables.
There could be several add_header directives. These directives are inherited from the previous configuration level if and only if there are no add_header directives defined on the current level.
If the always parameter is specified (1.7.5), the header field will be added regardless of the response code.
英文解释
在不添加always的情况下,add_header只对响应码为200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), 308 (1.13.0)这些生效(括号内是nginx版本)。也就是说当服务端返回响应异常,响应码不是上述之一的话,即使nginx有配跨域头信息,浏览器仍然会显示跨域错误。原因就是因为nginx对异常响应码添加add_header无效。