Spring Boot 允许跨域请求、自定义请求头

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%

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值