“Ajax请求后台,后台两次session不一致”问题解决

时间:2022-07-23
本文章向大家介绍“Ajax请求后台,后台两次session不一致”问题解决,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.问题

请求后台验证码接口,获取验证码和验证码校验的接口,校验时总是获取不到数值,就是两次的SESSIONID不一样

导致前端验证码数据传到后台,却取不到后台存储的验证码,无法进行校验

图片.png

2.解决

注意请求验证码图片的域名要和请求校验的域名一样,比如,localhost127.0.0.1是不一样的

1)前端

在请求中加入一个withCredentials: true就行了,意思就是跨域带cookie请求 Angularjs请求示例

    $scope.firstnext = function() {
        $http({
            method: "get",
            url: 'http://localhost:8083/contrastcode?verification=' + $scope.identycode,
            headers: {},
            withCredentials: true //!跨域带cookies
        }).then(function(req) {
            $log.log(req.data)
            if(req.data.valid == true){
                 //do somethings
            }
        })
    }

2)后台跨域解决

@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);
    }
}