前言
在本地做一个前后端分离小项目时,遇到了跨域问题,前端无法获得后端的数据。
一、解决办法
在前端后端都能解决跨域问题,作为后端学习者肯定是通过后端来进行解决。只需要在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项目即可解决跨域问题