前后端分离项目,前端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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:用springboot+vue搭建一个个人博客
下一篇:QT 项目的打包发部布后无发链接的sqlite数据库解决方法

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月23日 01时25分50秒