跨域:域名不一致就是跨域,主要包括:
域名不同: www.taobao.com 和www.taobao.org 和 www.jd.com 和 miaosha.jd.com
域名相同,端口不同: localhost:8080 和localhost8081
跨域问题:浏览器禁止请求的发起者与服务端发生跨域ajax请求,请求被浏览器拦截的问题。
究竟什么是跨域问题?
比如http://localhost:8090这个地址发起 http://localhost:10010/user/1 的get请求
该HTML文件在http://localhost:8090服务下启动 发送了http://localhost:10010/user/1 的get请求 请求被拒绝
<!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>
</pre>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios.get("http://localhost:10010/user/1?gateway=admin")
.then(resp => console.log(resp.data))
.catch(err => console.log(err))
</script>
</html>
解决方案:CORS 在网关配置信息文件添加如下内容
网关处理跨域采用的同样是CORS方案,并且只需要简单配置即可实现:
spring:
cloud:
gateway:
globalcors: #全局的跨域处理
add-to-simple-url-handler-mapping: true #解决options 请求被拦截问题
corsConfigurations:
'[/**]': #拦截哪些请求,/**表示拦截一切请求
allowedOrigins: #允许哪些网站的跨域请求
- "http://localhost:8090" #允许该地址 跨域对网关发送http://localhost:10010/user/1?gateway=admin
- "http://www.leyou.com"
allowedOrigins: #允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" #允许在请求中携带的头信息 *表示一切请求头
allowedCredentials: true #是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期
就是 从浏览器输入一个ip地址发送请求间接访问网关再去路由到其他服务。