Spring Boot 允許跨域請求、自定義請求頭
阿新 • • 發佈:2019-01-02
1:禁止跨域請求
Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘xxx’ is therefore not allowed access. The response had HTTP status code 403
2:禁止自定義請求頭
Request header field xxx is not allowed by Access-Control-Allow-Headers in preflight response
前後端分離,前端使用Ajax請求一般都會遇著這兩配置問題,在Spring Boot中新增如下配置
方式一
@Configuration
public class CorsConf {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*" );
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
方式二
在Application啟動類中註冊WebMvcConfigurer
@Bean
public WebMvcConfigurer webMvcConfigurer () {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}