1、首先破除一个误区,https、http相互访问请求,或者其他不同源请求,浏览器会不会直接将其拦截,从而到不了服务端?
答:浏览器绝对不会将接口请求拦截,可以放心。但是请求到服务器有可能是2次,第一次options预请求,第二次才是正真的get/post请求。
2、所有的跨域问题,只需要在nginx或者服务器端中的一端,加允许跨域即可
nginx配置如下(下面代码可以卸载server内也可以写在location内):
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
or Java服务端代码:Spring4.2以上使用全局xml文件配置
<mvc:cors>
<mvc:mapping path="/**"
allowed-origins="*"
allow-credentials="true"
allowed-methods="*"
allowed-headers="Origin,X-Requested-With,Content-Type,Accept"
max-age="3600" />
</mvc:cors>
3、强调一下常见的跨域,第一是不同域名的访问,第二是https于http之间的相互访问,详情看浏览器不同源策略。