1、跨域介绍
域:由协议、ip、端口组成
可分为两种:
1.同域:协议、ip、端口都相同
2.跨域:协议、ip、端口只要有一个不同,违反浏览器的同源策略
说一下同源策略:
同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。
跨域目前只会出现在Ajax异步访问
10.31.160.100 通过ajax去访问 10.31.160.101:8080/aa/bb 这个资源,就会出现跨域
场景:1.有网关如何解决跨域问题
比如:有一个 index.html 页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<pre>
spring:
cloud:
gateway:
globalcors: # 全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
corsConfigurations:
'[/**]':
allowedOrigins: # 允许哪些网站的跨域请求
- "http://localhost:8090"
- "http://www.leyou.com"
allowedMethods: # 允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息
allowCredentials: true # 是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期
</pre>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios.get("http://localhost:10010/user/1?token=admin")
.then(resp => console.log(resp.data))
.catch(err => console.log(err))
</script>
</html>
把它放到nginx中
接着在网关配置文件*.yaml中增加如下内容
spring:
cloud:
gateway:
# 一定要复制
globalcors: # 全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
corsConfigurations:
'[/**]':
allowedOrigins: # 允许哪些网站的跨域请求,如果是80端口,不要写端口号
- "http://localhost:8090"
- "http://127.0.0.1:8090"
- "http://localhost"
- "http://127.0.0.1"
allowedMethods: # 允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息
allowCredentials: true # 是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期
场景:2.没有网关如何解决跨域问题,通过springmvc提供的@CrossOrigin注解
加在提供者的类上,这样可以通过远程调用提供者的方法拿到返回数据