什么是跨域
只要 协议 , 主机/域名/IP , 端口号 有任何一个不同, 那么就是跨域 ;
跨域 :
http://localhost:9001/brand
https://localhost:9001/brand
http://192.168.190.129:9001/brand
http://192.168.190.128:9001/brand
http://192.168.190.129:9001/brand
http://192.168.190.129:9002/brand
默认情况下 , 受浏览器同源策略影响 , Ajax是不能够跨域请求数据的 , 如果跨域请求, 则会包以下错误 :
解决方案CORS
CORS - Cross Origin Resource Sharing 跨域资源共享 ; 是W3C标准 , 而该标准是后来提出来的 , 所以在早期的浏览器(IE10版本之前)中, 是不支持CORS的 ;
使用:
@CrossOrigin
作用在类上; 也可以作用在方法上 ;
该注解式Spring4.2版本之后提供 ;
如果使用最为原始的方式解决跨域 :
@GetMapping
public Result findAll(HttpServletResponse response){
response.addHeader("Access-Control-Allow-Origin","*");
List<Brand> brandList = brandService.findAll();
return new Result(true, StatusCode.OK,"查询成功",brandList) ;
}
其他的跨域的解决方案 :
1). JSONP
2). 代理
3). CORS
服务网关中跨域的解决
spring:
application:
name: sysgateway # 应用在eureka中注册的名称
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]': # 匹配所有的请求
allowedOrigins: "*" # 跨域处理,允许所有的域进行跨域
allowedMethods: # 允许支持跨域的方法
- GET
- POST
- PUT
- DELETE