須要解決前端pc跟服務端(java),跨域後都能獲取到同一個cookie。
使用二級域名共享cookie有一個限制條件,就是兩個域名的二級域名必須相同前端
前端pc訪問域名:a.b.com
後端接口域名:a-gateway.b.com
這兩個域名同屬一個二級域名:b.comvue
服務器nginx增長如下配置,便可解決跨域訪問的問題。也能夠在程序中經過代碼解決跨域訪問。java
location / {
#是否容許跨域發送Cookie
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Origin 'http://a.b.com';
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}
複製代碼
若是須要容許跨域攜帶發送cookie的話,nignx則須要如下參數配置ios
import axios from 'axios';
axios.defaults.withCredentials=true //容許攜帶cookie
複製代碼
public static void addCookie(HttpServletResponse response,String cookieName,String cookieValue,int maxAge){
Cookie cookie =new Cookie(cookieName,cookieValue);
cookie.setDomain("b.com");//指定域名
cookie.setPath("/");//設置cookie的生命週期
cookie.setHttpOnly(false);
if(maxAge>0){
cookie.setMaxAge(maxAge);
}
response.addCookie(cookie);
}
複製代碼