SpringBoot 解决 Ajax 跨域之 session 问题

博客指出前后端分离写网站时,使用 ajax 跨域请求会创建两个 session ,无法实现数据存入 session 共享。并给出解决办法,前端有关键代码,后端关键代码为 setAllowCredentials(true)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

由于使用前后端分离写网站,不可以避免的会使用 ajax 进行跨域请求,但发现两次请求都会创建两个 session ,无法达到将数据存入 session 实现数据共享的效果。

问题解决:

前端:最主要的是下面这行代码?:

xhrFields: {
         withCredentials: true
}
$.ajax({
        type: 'POST',
        url: rootPath + '/manager/login',
        dataType: 'JSON',
        xhrFields: {
               withCredentials: true
        },
        data: {
              username: username,
              password: password,
              verifyCode: verifyCode
        },
        success: function(result) {
                 console.log(result)         
        },
        error: function(error) {
               console.log(error)
        }
});

后端:最主要的是 setAllowCredentials(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;

@Configuration
public class CustomCORSConfiguration {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值