在前后端分享的项目中经常遇到跨域问题,我自己使用的这种方法解决此问题,可供大家参考
首先在Controller层里添加@CrossOrigin注解
不过发现还需要创建一个Config类(可选择新建config文件夹,然后新建如WebMvcConfig类)
代码如下:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//设置允许跨域的路径
registry.addMapping("/**")
//设置允许跨域请求的域名
.allowedOrigins("http://127.0.0.1:8080")
//是否允许证书 不再默认开启
.allowCredentials(true)
//设置允许的方法
.allowedMethods("*")
//跨域允许时间
.maxAge(3600);
}
}
至于允许跨域的地址可在.allowedOrigins里配置,也可在@CrossOrigin注解直接添加,如
@CrossOrigin(origins = {"http://127.0.0.1:5173/"})