Go语言 无法从主域访问子域:无“Access-Control-Allow-Origin”

eimct9ow  于 2023-04-09  发布在  Go
关注(0)|答案(1)|浏览(187)

版本

go 1.17
github.com/gin-contrib/cors v1.3.1
github.com/gin-gonic/gin v1.7.7

问题

我在我的子域中运行在REST API服务器上。
React应用程序放置在主域中,使用GET方法和POST方法访问API服务器,但获得cors策略错误Access to XMLHttpRequest at 'https://<subdomain>.<domain>.xxx/api/v1/users' from origin 'https://<domain>.xxx' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
在网络搜索中,我发现了同样的问题和一些解决方案,但它们在我的情况下不起作用。

代码

所有这些程序都出现了相同的错误。

案例一

package gateway

import (
    "log"

    "github.com/gin-contrib/cors"
    "github.com/gin-gonic/gin"
)

func RunServer() {
    r := gin.Default()
    r.Use(cors.Default())
    api := r.Group("/api")
    v1 := api.Group("/v1")
    userRouters(v1)
    err := r.Run()
    if err != nil {
        log.Printf("failed to run gateway: %v", err)
    }
}

用例2

package gateway

import (
    "log"
    "time"

    "github.com/gin-contrib/cors"
    "github.com/gin-gonic/gin"
)

func RunServer() {
    r := gin.Default()
    r.Use(cors.New(cors.Config{
        AllowOrigins:     []string{"*"},
        AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
        AllowHeaders:     []string{"Content-Type"},
        AllowCredentials: false,
        MaxAge:           12 * time.Hour,
    }))
    api := r.Group("/api")
    v1 := api.Group("/v1")
    userRouters(v1)
    err := r.Run()
    if err != nil {
        log.Printf("failed to run gateway: %v", err)
    }
}

案例三

响应标头中缺少Access-Control-Allow-Origin。·问题#29 · gin-contrib/cors

package gateway

import (
    "log"

    "github.com/gin-gonic/gin"
)

func CORS() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }

        c.Next()
    }
}

func RunServer() {
    r := gin.Default()
    r.Use(CORS())
    api := r.Group("/api")
    v1 := api.Group("/v1")
    userRouters(v1)
    err := r.Run()
    if err != nil {
        log.Printf("failed to run gateway: %v", err)
    }
}

从终端进行预检

> curl 'https://alb.skhole.club/api/v1/authz' \
  -X 'OPTIONS' \
  -H 'authority: alb.skhole.club' \
  -H 'accept: */*' \
  -H 'accept-language: ja,en-US;q=0.9,en;q=0.8' \
  -H 'access-control-request-headers: content-type' \
  -H 'access-control-request-method: POST' \
  -H 'cache-control: no-cache' \
  -H 'origin: https://skhole.club' \
  -H 'pragma: no-cache' \
  -H 'referer: https://skhole.club/' \
  -H 'sec-fetch-dest: empty' \
  -H 'sec-fetch-mode: cors' \
  -H 'sec-fetch-site: same-site' \
  -H 'user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36' \
  --compressed -i
HTTP/2 502 
server: awselb/2.0
date: Wed, 05 Apr 2023 04:04:13 GMT
content-type: text/html
content-length: 524

<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
</body>
</html>
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->

已解决

这是由aws_lb_target_group设置引起的。
我在目标组中设置了HTTPS协议,尽管我只为Route 53和ALB提供了ACM证书。
我用HTTP替换了HTTPS,现在它可以工作了。

9gm1akwq

9gm1akwq1#

诊断此类问题的第一步是直接检查Chrome DevTools中的preflight请求。

备注

1.检查Disable cache,以防预处理响应被缓存。
1.查找类型为preflight的请求。
下一步是将preflight请求复制为curl命令(右键单击请求,在上下文菜单中选择Copy-〉Copy as cURL),并直接使用curl工具测试请求(记住修改命令以添加-i选项来打印响应头)。
看起来你在生产环境中遇到了这个问题,可能是浏览器和你的服务之间的反向代理默认阻止了Access-Control-Allow-Origin头。尝试直接向你的服务发送preflight请求,看看是否有什么不同。

更新(提供预检响应后):

事实证明,这根本不是CORS问题。请求失败,状态代码为502 Bad Gateway。应用程序没有正确部署。
顺便说一句,我已经测试了案例1,它的工作原理:

package main

import (
    "log"
    "net/http/httputil"

    "github.com/gin-contrib/cors"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.Use(cors.Default())
    api := r.Group("/api")
    v1 := api.Group("/v1")
    v1.POST("users", func(ctx *gin.Context) {
        buf, err := httputil.DumpRequest(ctx.Request, true)
        if err != nil {
            log.Printf("failed to dump request: %v", err)
            return
        }

        log.Printf("%s", buf)
    })
    err := r.Run()
    if err != nil {
        log.Printf("failed to run gateway: %v", err)
    }
    r.Run()
}
$ curl 'http://localhost:8080/api/v1/users' \
  -X 'OPTIONS' \
  -H 'Accept: */*' \
  -H 'Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6' \
  -H 'Access-Control-Request-Headers: content-type' \
  -H 'Access-Control-Request-Method: POST' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Origin: http://127.0.0.1:5501' \
  -H 'Pragma: no-cache' \
  -H 'Referer: http://127.0.0.1:5501/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: cross-site' \
  -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36' \
  --compressed -i
HTTP/1.1 204 No Content
Access-Control-Allow-Headers: Origin,Content-Length,Content-Type
Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 43200
Date: Wed, 05 Apr 2023 03:50:06 GMT

相关问题