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

2020-08-25 14:49:41 浏览数 (1)

1.问题

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

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

图片.png

2.解决

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

1)前端

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

代码语言:javascript复制
    $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)后台跨域解决

代码语言:javascript复制
@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);
    }
}

0 人点赞