在springboot中解决跨域问题,亲自尝试有以下几种:
1) 设置response对象的header
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Origin", "http://localhost:8080");
response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT");
2) 添加注解在controller或method上
@CrossOrigin(origins = "http://localhost:8080",methods = RequestMethod.POST,allowCredentials = "true")
3)增加一个bean,重写WebMvcConfigurer
@Configuration
public class GlobalCorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
//放行哪些原始域
.allowedOrigins("*")
//是否发送Cookie信息
.allowCredentials(true)
//放行哪些原始域(请求方式)
.allowedMethods("GET","POST", "PUT", "DELETE");
}
};
}
}
以上3种方法,亲测可行。