解决前后端分离 vue+springboot 跨域 session+cookie失效

前端 vue ip地址:192.168.1.205

后端 springboot2.0 ip地址:192.168.1.217

主要开发后端。

问题:

首先登陆成功时将用户存在session中,后续请求在将用户从session中取出检查。后续请求取出的用户都为null。

解决过程:

首先发现sessionID不一致,导致每一次都是新的会话,当然不可能存在用户了。然后发现cookie浏览器不能自动保存,服务器响应set-cookie了

解决前后端分离 vue+springboot 跨域 session+cookie失效

搜索问题,发现跨域,服务器响应的setCookie浏览器无法保存,而且就算保存了域名不同也不能携带。

第一步:

后台添加过滤器,因为前后端分离,不可能每个方法都写一遍,所以添加过滤器统一处理。

package com.test.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebFilter(urlPatterns = "/*", filterName = "CORSFilter") public class CORSFilter implements Filter { @Override public void destroy() { } /** * 此过滤器只是处理跨域问题 * @param servletRequest * @param servletResponse * @param chain * @throws ServletException * @throws IOException */ @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest) servletRequest; HttpServletResponse resp = (HttpServletResponse) servletResponse; String origin = req.getHeader("Origin"); if(origin == null) { origin = req.getHeader("Referer"); } resp.setHeader("Access-Control-Allow-Origin", origin);//这里不能写*,*代表接受所有域名访问,如写*则下面一行代码无效。谨记 resp.setHeader("Access-Control-Allow-Credentials", "true");//true代表允许携带cookie chain.doFilter(servletRequest,servletResponse); } @Override public void init(FilterConfig filterConfig) throws ServletException { } }

springboot2.配置过滤器时,启动类必须加上@ServletComponentScan才会加载过滤器

@SpringBootApplication @EnableTransactionManagement(order = 10) @ServletComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

然后前端配置

使用vue.resource发送请求时配置如下: main.js中 Vue.http.options.xhr = { withCredentials: true } 使用vue.axios发送请求时配置如下: axios.defaults.withCredentials = true; jquery请求带上 xhrFields: {withCredentials: true}, crossDomain: true; $.ajax({ type: "post", url: "", xhrFields: {withCredentials: true}, crossDomain: true, data: {username:$("#username").val()}, dataType: "json", success: function(data){ } });

此时问题已解决。

但我查看请求时,还是没有带cookie,太纠结于这一点了。以至于查看全部cookie时突然明白了。

解决前后端分离 vue+springboot 跨域 session+cookie失效

没有带cookie。

浏览器全部cookie

解决前后端分离 vue+springboot 跨域 session+cookie失效

已经有服务器的cookie了。当向服务器发送请求时,会携带cookie,证明是同一会话。

发现火狐的请求头中存在cookie,不知道为什么谷歌的请求头不显示,不明白。望解答。

解决前后端分离 vue+springboot 跨域 session+cookie失效

总结

以上所述是小编给大家介绍的解决前后端分离 vue+springboot 跨域 session+cookie失效问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/bdc79f697aa4604dc032ad604e9f58ee.html