一.简述
1.跨域:是为了阻止跨站攻击,浏览器对于ajax请求的一种安全限制
2.种类:
- 域名不同的跨域。
- 域名相同、端口不同的跨域。
- 二级域名不同的跨域。
二.解决
这个问题很常见,做前后端分离开发基本都会遇到,网上也有很多解决办法。
我的解决方案,创建一个配置类就行了。
我遇到的问题:新版本springboot报错,将allowedOrigins替换成.allowedOriginPatterns即可
嫌麻烦的话,可以直接在controller层直接添加@CrossOrigin 不用写CrosConfig相关,添加跨域注解
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 CrossConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// WebMvcConfigurer.super.addCorsMappings(registry);
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}