【无标题】

前言
在本地做一个前后端分离小项目时,遇到了跨域问题,前端无法获得后端的数据。

一、解决办法
在前端后端都能解决跨域问题,作为后端学习者肯定是通过后端来进行解决。只需要在SpringBoot项目中配置跨域请求配置类即可解决(这种方式是全局配置的):

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")    // 配置跨域请求支持的方式
                .allowCredentials(true)    // 配置是否允许发送Cookie,用于 凭证请求, 默认不发送cookie
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

以下代码已经不推荐使用, WebMvcConfigurerAdapter 在SpringBoot2.x中已经被标记为过时,Spring5以下的版本建议使用这段代码

@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**").allowedOrigins("*")
				.allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
				.allowCredentials(true)
				.maxAge(3600);
	}
}

点进源码可以看到:

**
 * An implementation of {@link WebMvcConfigurer} with empty methods allowing
 * subclasses to override only the methods they're interested in.
 *
 * @author Rossen Stoyanchev
 * @since 3.1
 * @deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made
 * possible by a Java 8 baseline) and can be implemented directly without the
 * need for this adapter
 */
@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {}

像这种过时的类或者方法,作者们一定会在注解上面说明原因,并告诉应该使用哪个方法。

spring5最低支持到jdk1.8,所以注释中明确表明,你可以直接实现WebMvcConfigurer接口,无需再用这个适配器,因为jdk1.8支持接口中存在default-method。

二、重启SpringBoot项目即可解决跨域问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值