后端:springboot的跨域设置,这里需要允许cookies等 .allowCredentials(true)
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路由
registry.addMapping("/**")
// 设置允许跨域请求的域名
.allowedOrigins("*")
// 再次加入前端Origin localhost!=127.0.0.1
.allowedOrigins("http://localhost:8080")
// 是否允许证书(cookies)
.allowCredentials(true)
// 设置允许的方法
.allowedMethods("*")
//允许请求头
.allowedHeaders("*")
// 跨域允许时间
.maxAge(3600);
}
};
}
}
前端:在封装好的axios添加 withCredentials: true, //允许session跨域
import axios from 'axios'
const request = axios.create({
withCredentials: true, //允许session跨域
baseURL: 'http://localhost:9090', // 注意!! 这里是全局统一加上了 '/api' 前缀,也就是说所有接口都会加上'/api'前缀在,页面里面写接口的时候就不要加 '/api'了,否则会出现2个'/api',类似 '/api/api/user'这样的报错,切记!!!
timeout: 5000
})