前后端分离项目,前端cookie获取不到的解决方案
发布日期:2022-03-08 21:50:42
浏览次数:4
分类:技术文章
本文共 1698 字,大约阅读时间需要 5 分钟。
最近在写前后端分离项目中发现,后端在response中添加cookie后
response.addCookie(cookie)
前端却无法拿到cookie,但是在网络抓包中确实存在cookie
但是在Application中却找不到cookie
判断错误出在跨域上,因为我前端是8080接口,后端是9090,所以后端保存的cookie前端有接受到,但是无法保存。
解决问题是在跨域配置中将Credentials属性设置为true,一开始我的跨域配置中没有这个属性。
后端配置的跨域文件:
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;@Configurationpublic class CorsConfig { // 当前跨域请求最大有效时长。这里默认1天 private static final long MAX_AGE = 24 * 60 * 60; private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowCredentials(true); //允许接受cookie corsConfiguration.addAllowedOriginPattern("*"); // 1 设置访问源地址 corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头 corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法 corsConfiguration.setMaxAge(MAX_AGE); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置 return new CorsFilter(source); }}
注意:添加 corsConfiguration.setAllowCredentials(true); 后,要把原来的
corsConfiguration.addAllowedOrigin("*");
改成:
corsConfiguration.addAllowedOriginPattern("*");
前端配置(这里我用的是axios请求):
单次配置:
request.post("http://localhost:9090/login", this.form, {withCredentials: true}) .then((res) => {}
统一配置
axios.defaults.withCredentials = true;
配置完就可以拿到cookie了
转载地址:https://blog.csdn.net/m0_55543463/article/details/122157049 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2024年04月23日 01时25分50秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
A* Pathfinding Project (Unity A*寻路插件) 使用教程
2019-04-27
bash学习笔记
2019-04-27
sqlite学习
2019-04-27
手把手教你实现Unity与Android的交互
2019-04-27
手把手教你使用Unity的Behavior Designer
2019-04-27
Unity3D摄像机裁剪——NGUI篇
2021-06-30
lua深拷贝一个table
2021-06-30
app运行提示Unable to Initialize Unity Engine
2021-06-30
spring boot 与 Ant Design of Vue 实现修改按钮(十七)
2021-06-30
spring boot 与 Ant Design of Vue 实现删除按钮(十八)
2021-06-30
spring boot 与 Ant Design of Vue 实现新增角色(二十)
2021-06-30
spring boot 与 Ant Design of Vue 实现修改角色(二十一)
2021-06-30
spring boot 与 Ant Design of Vue 实现删除角色(补二十一)
2021-06-30
spring boot 与 Ant Design of Vue 实现左侧组织树(二十三)
2021-06-30
spring boot 与 Ant Design of Vue 实现新增组织(二十四)
2021-06-30
spring boot 与 Ant Design of Vue 实现修改组织(二十五)
2021-06-30
spring boot 与 Ant Design of Vue 实现删除组织(二十六)
2021-06-30