起因
想必并不是前后端一定处于一个同域的状态,可能有以下情况:
这样就容易遇见一个这样的问题,后端想基于Session来存储和使用数据,可这个时候就根本拿不到SessionID。
就像我刚刚那样,明明后端已经配好了CORS,前端还是有问题。
解决办法
前端
1 2 3 4 5 6 7 8 9
| axios.defaults.baseURL = 'http://localhost:8080'; axios.interceptors.request.use(config => { config.withCredentials=true return config }, error => { return Promise.reject(error); });
|
后端
1 2 3 4 5 6 7 8 9 10 11 12
| @Value("${lnpbqc.allowCORS}") String allowCORS;
@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins(allowCORS) .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); }
|
结果
可以正常拿到SessionID,进而存储和使用数据了。