问题描述:
前端网址:http://h5.xxx.com,后端网址:http://gateway.yyy.com
前端使用axios发送ajax请求到后端,
后端使用Spring Boot,拦截器中查看到每次请求的session id都不一样,每次response的set-cookie中都包含有"SESSIONID"参数,很明显是因为前端没有把sessionid通过cookie传递给后端。
解决方案
前端请求中增加:
class="javascript">
const obj = Object.assign({}, config, {
headers,
withCredentials: true,
crossDomain: true,
});
后端拦截器:
HttpServletResponse servletResponse = (HttpServletResponse) response;
servletResponse.setContentType("application/json; charset=utf-8");
servletResponse.setCharacterEncoding("UTF-8");
// 特别注意:Access-Control-Allow-Origin值不能为*,而应该是一个具体的值
// 否则cookie一样传递不过来
// 这里直接用request.getHeader("Origin"),其实产生的作用跟*基本一致
servletResponse.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
servletResponse.addHeader("Access-Control-Allow-Credentials", "true");
servletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,Cookies");
if (request.getHeader("Access-Control-Request-Method") != null
&& "OPTIONS".equals(request.getMethod())) {// CORS "pre-flight" request
servletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
servletResponse.addHeader("Access-Control-Max-Age", "7200");
servletResponse.setStatus(200);
servletResponse.getWriter().write("OK");
return;
}