JS跨域请求接口登录状态失效解决方案

JS跨域请求接口时,默认是不保存cookie的,需要前后端都配置一下。

spring拦截器

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
    static final String ORIGINS[] = new String[]{"GET", "POST", "PUT", "DELETE"};

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS)
                .maxAge(3600);
    }
}

JS请求需要配置withCredentials:true
例如:

$.ajax({
 type : "POST",
 url : 'https://xxxx:8080/app/company/queryList',
 dataType : "JSON",
 data : "",
 xhrFields: {withCredentials: true},
 success : function(res){
 }
});

http.post("https://xxxx:8080/app/company/queryList",this.user,{withCredentials:true})
      .toPromise()
      .then(response=>{console.log(response);return response.text()});

参考资料 https://segmentfault.com/a/1190000012469713

2 条评论

[/0o0] [..^v^..] [0_0] [T.T] [=3-❤] [❤.❤] [^v^] [-.0] [!- -] [=x=] [→_→] [><] 更多 »
昵称
  1. @ Google Chrome 69 Google Chrome 69 Windows 10 Windows 10

    前两天网站挂了吧

    1. 鸽子 鸽子 Google Chrome 70 Google Chrome 70 Windows 10 Windows 10

      前两天在迁移网站