跨域资源共享(CORS)是前后端分离项目很常见的问题,本文主要是介绍在Springboot项目中通过cors协议解决跨域问题
CORS协议
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。
它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
解决方案
1.基于WebMvcConfigurerAdapter配置加入Cors的跨域
通过实现WebMvcConfigurer接口中的addCorsMappings方法来实现跨域
/**
* 跨域配置类
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")//*表示允许任何域名使用
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")
.maxAge(3600);
}
}
- addMapping:配置可以被跨域的路径,可以任意配置