失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Google浏览器跨域不能设置cookie问题

Google浏览器跨域不能设置cookie问题

时间:2023-01-04 16:31:52

相关推荐

Google浏览器跨域不能设置cookie问题

在前后端分离的项目中Google浏览器中不能设置cookie,因为在Google浏览器80版本后增加了SameSite的cookie限制,默认为Lax模式不携带cookie和session。

解决这一问题的方法就是在正确配置springboot和vue的跨域配置的前提下做本地的域名映射,将本地的localhost地址映射成一个自定义的域名,不需要使用nginx做代理,直接通过访问域名进行联调测试。

(方案参考百度sso登录)

需要在后端设置cookie时指定上域名,并且前端的接口调用也要使用此域名才能正常设置cookie。

因为cookie设置成功的自然而然session也就可以用了。

springboot跨域配置

import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** @author: WangKangSheng* @create: -11-22 15:31* 跨域配置*/@Configurationpublic class CorsConfiguration implements WebMvcConfigurer {/*** Configure cross origin requests processing.* @param registry CorsRegistry*/@Override public void addCorsMappings(CorsRegistry registry) {System.out.println("跨域配置");registry.addMapping("/**") // 设置跨域的路径.allowedOrigins("*") // 源头.allowedMethods("*") // 方法.allowCredentials(true) // session和cookie.exposedHeaders("Access-Control-Allow-Origin","Access-Control-Allow-Credentials").maxAge(3600); // 请求的响应时间}}

前端vue中axios的配置代码

在main.js中设置可携带cookie和session。

import axios from 'axios'axios.defaults.withCredentials=true;

效果:

一切正常。(前面两个域名是线上的和本地的localhost测试域名)

如果觉得《Google浏览器跨域不能设置cookie问题》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。