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("*");
}
};
}
推荐文章:
1:【代码规范神器】阿里巴巴Java开发规约IDE插件使用教程(P3C)
2:Eclipse新建Spring-boot项目,打包部署并输出HelloWord
3:程序员如何脱单?看完脱单率至少增加80%