跨域:域名不一致就是跨域,主要包括:
-
域名不同: www.taobao.com 和 www.taobao.org 和 www.jd.com 和 miaosha.jd.com
-
域名相同,端口不同:localhost:8080和localhost:8081
跨域问题:浏览器禁止请求的发起者与服务端发生跨域ajax请求,请求被浏览器拦截的问题
- 有网关的情况下
解决方案:CORS
在服务端进行配置:在gateway的application.yaml中添加配置
spring:
cloud:
gateway:
globalcors: # 全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
corsConfigurations:
'[/**]':
allowedOrigins: # 允许哪些网站的跨域请求
- "http://localhost:8090"
allowedMethods: # 允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息
allowCredentials: true # 是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期
-
SpringBoot框架下
在SpringBoot的Controller层中可以通过@CrossOrigin
注解来实现跨域访问控制,只需要在方法上添加该注解即可。
@CrossOrigin注解中的origins属性表示允许跨域请求的源地址,多个地址可以用逗号分隔。如果不指定该属性,则表示允许所有来源的请求。 -
实现WebMvcConfigurer接口
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/user/**")
.allowedOrigins("http://localhost:8080")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true)
.maxAge(3600);
}
}
- mapping: 允许跨域访问的映射路径
- origins: 允许访问的来源
- methods: 允许访问的HTTP方法
- credentials: 是否允许发送Cookie
- maxage: 响应的缓存时间