cors跨域问题解决
golang后端框架gin如果设置了分组的group请求前缀,跨域有些不一样。
r1 := gin.Default()r := r1.Group("/game")webSocket := server.NewWebSocket()r1.NoRoute(cors.New(cors.Config{AllowOrigins: allowOrigins,AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},AllowHeaders: []string{"*",},AllowCredentials: true,MaxAge: 12 * time.Hour,},))// websocket单独处理,正常http请求按照router.Register方式来写r.Use(cors.New(cors.Config{AllowOrigins: allowOrigins,AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},AllowHeaders: []string{"*",},AllowCredentials: true,MaxAge: 12 * time.Hour,},),).Use(TraceIDHandler()).Use(timeoutMiddleware()).Use(gin.CustomRecovery(customRecoveryHandler)).Use(RequestUserInfo()).Use(RequestLogMiddleware()).Use(ResponseHeaderSet())
r.Group.POST(path, r.Handle)
通过查看
r.Group.POST(path, r.Handle)的源码得知:
func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {absolutePath := group.calculateAbsolutePath(relativePath)handlers = group.combineHandlers(handlers)group.engine.addRoute(httpMethod, absolutePath, handlers)return group.returnObj()
}
如果写了
r.POST(path, r.Handle),则以上源码中的 group.engine.addRoute(httpMethod, absolutePath, handlers) 只会将post方法对应的跨域用的cors的handler来处理注册到engine中。而对于options方法的请求是不会用这个handlers来处理的。
如果想解决此问题,有两个方案:
1. 对于post/get等请求,不只是写
r.POST(path, r.Handle),而是增加r.OPTIONS(path, r.Handle),将options也写入到engine的处理的method中
2. 增加这个方法:
r1.NoRoute(cors.New(cors.Config{AllowOrigins: allowOrigins,AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},AllowHeaders: []string{"*",},AllowCredentials: true,MaxAge: 12 * time.Hour,}, ))
这是告诉engine。如果存在不理解的method。则用norout中定义的hanlder处理。那么我们这里定义了cors的hanlder方法。因为options没有在engine中注册过,因此会采用这个noroute中注入的hanler cors来处理。也满足条件。我在代码中就是用的这种方式
二. 进入cros的判断
如果前端发送请求时没有配置credentials: 'include'。则前端的header中即使有'Authorization': 'Bearer xxxx'头,浏览器依然不认为则是一个'带有凭据'的请求。
1. 如果不设置credentials: 'include',则后端设置AllowOrigins具体的域名,AllowHeaders设置为*,都可以通过跨域请求
但是如果如下设置:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>跨域测试页面</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<h1>跨域测试</h1>
<div>
<input type="button" οnclick="mySubmit()" value=" 发送跨域请求 ">
</div>
<script>
function mySubmit() {
fetch("http://localhost:8082/game/v1/new_game", {
method: "POST",
credentials:"include",
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'Bearer xxxx'
},
body: JSON.stringify({"name": "Java"})
})
.then(response => response.json())
.then(result => alert("返回数据:" + result.data))
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>
增加了credentials:"include",
根据cors的规范:
禁止在Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true的时候,前端发送带有凭据的请求能够通过cros。
2. 实际测试过程中发现会更严格;
即使设置了AllowOrigins,但是AllowHeaders设置为*。也是无法通过跨域请求的。
r1.NoRoute(cors.New(cors.Config{AllowOrigins: allowOrigins,AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},AllowHeaders: []string{"*",},AllowCredentials: true,MaxAge: 12 * time.Hour,}, ))
必须指定AllowHeaders。同时,不能只设置r1.NoRoute,对实际的post请求也要设置好,也就是
r.Use(也要对AllowHeaders进行指定。
3. 通过测试来看,似乎前端不增加 credentials:"include",的话,后端的
AllowHeaders选择通配符是能够跨域成功的。