前端后端都需要开启允许跨源访问
修改前端
Vue使用axios请求时加上withCredentials=true
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| export function request(config) { const instance = axios.create({ baseURL: 'http://192.168.43.215:8084/', timeout: 5000, withCredentials:true, }) instance.interceptors.request.use(config => { return config }, err => { console.log(err); }) instance.interceptors.response.use(res => { return res.data }, err => { console.log(err); })
return instance(config) }
|
修改后端
2.4以前的版本:
后端springboot需要重写配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Configuration public class CorsConfig implements WebMvcConfigurer {
@Override public void addCorsMappings(CorsRegistry registry) { System.out.println("----------------------"); registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("*") .maxAge(3600); }
}
|
在使用的接口类前面写上注释
2.4之后的版本
SpringBoot升级2.4.0所出现的问题:When allowCredentials is true, allowedOrigins cannot contain the specia
解决办法1:降低springboot版本
解决办法2:
将上述allowedOrigins(“*”),
改成.allowedOriginPatterns(“*”)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Configuration public class CorsConfig implements WebMvcConfigurer {
@Override public void addCorsMappings(CorsRegistry registry) { System.out.println("----------------------"); registry.addMapping("/**") .allowedOriginPatterns("*") .allowCredentials(true) .allowedMethods("*") .maxAge(3600); } }
|