存在问题
页面依次发起多次请求,服务端会根据有无携带Set-Cookie从而生成新的JSESSIONID返回,前端需要在后续请求自动携带该值(浏览器行为,无需代码控制)
但目前的情况为:前端请求无法自动携带,每次都生成新的JSESSIONID,导致服务端无法判断是否同一用户。
分析问题:
问题修改:
前端:
本地开启跨域配置
proxy: {'/server': {target: 'http://192.168.1.80:8080/',changeOrigin: true,secure: false,pathRewrite: { '^/server': '' },},},
请求库设置允许跨域携带cookie
- axios
// 请求配置文件
const config = {baseURL: domain,timeout: 1000 * 15,withCredentials: true,maxRedirects: 3,headers: {"Content-Type": " application/json;charset=UTF-8",},
};// 创建ajax实例
const instance = axios.create(config);
- request
const defaultOptions = {credentials: 'include',};const newOptions = { ...defaultOptions, ...options };
return fetch(url, newOptions).then(checkStatus).then(response => cachedSave(response, hashcode)).then(response => {// DELETE and 204 do not return data by default// using .json will report an error.if (newOptions.method === 'DELETE' || response.status === 204) {return response.text();}return response.json();})
后端
httpServletResponse.setHeader("Access-Control-Allow-Origin",httpServletRequest.getHeader("origin"));
httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,X-App-Id, X-Token");
httpServletResponse.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
配置
cookie的path为本项目存在此问题,其他项目不一定,如无问题,本步骤可忽略
至此发现可以拿到cookie,但是请求仍然无法携带过去,从浏览器的f12可以看到请求的cookie被过滤:
此Cookie已被屏蔽,因为它的路径与请求网址的路径不完全匹配或不是其超目录
这时有两个方案:
修改tomcat
修改tomcat下.conf/下context.xml文件
<Context sessionCookiePath="/"/>
修改项目
项目接口请求拦截器里设置
cookie.setPath("/");//设置作用域