首頁 > 後端開發 > Golang > 主體

無法從主網域存取子網域:沒有'Access-Control-Allow-Origin”

WBOY
發布: 2024-02-09 18:30:16
轉載
735 人瀏覽過

無法從主網域存取子網域:沒有Access-Control-Allow-Origin”

php小編小新今天為大家介紹的是一個常見的網頁開發問題:無法從主網域存取子網域,出現了「Access-Control-Allow-Origin」錯誤。這個問題在前端開發中經常遇到,尤其在跨域請求時較為常見。它通常會導致請求被瀏覽器攔截,無法正常取得所需的資料。在本文中,我們將詳細解釋這個錯誤的原因和解決方法,幫助大家快速解決這個問題,確保專案的正常運作。

問題內容

版本

go 1.17
github.com/gin-contrib/cors v1.3.1
github.com/gin-gonic/gin v1.7.7
登入後複製

問題

我在我的子網域中運行 gin rest api 伺服器。

react應用程式放置在主網域中,使用get方法和post方法存取api伺服器,但出現cors策略錯誤access to xmlhttprequest at 'https://<subdomain>.<domain>.xxx/api/ v1/users' from origin 'https:// /<domain>.xxx' 已被cors 策略阻止:對預檢請求的回應未透過存取控制檢查:請求的資源. 上不存在「access- control-allow-origin」標頭。

在網路搜尋中,我發現了同樣的問題和一些解決方案,但它們對我的情況不起作用。

程式碼

所有這些程式都出現相同的錯誤。

案例1

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)
    }
}

登入後複製

案例3

回應標頭中缺少 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 設定引起的。

儘管我僅向 route 53 和 alb 提供了 acm 證書,但我在目標群組中設定了協定 https。

我用 http 替換了 https,現在它可以工作了。

解決方法

診斷此類問題的第一步是直接檢查 chrome devtools 中的預檢請求。

註解

  1. 檢查 disable cache 以防預檢回應被快取。
  2. 尋找類型為preflight的請求。

下一步是將預檢請求複製為curl 命令(右鍵單擊請求,在上下文選單中選擇copy->copy as curl )並直接使用curl 工具測試請求(記得修改指令新增-i 選項用於列印回應標頭)。

您似乎在生產環境中遇到了該問題,瀏覽器和您的服務之間的反向代理可能預設阻止 access-control-allow-origin 標頭。嘗試將預檢請求直接發送到您的服務,看看是否有任何不同。

更新(提供預檢回應後):

事實證明,這根本不是 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
登入後複製

以上是無法從主網域存取子網域:沒有'Access-Control-Allow-Origin”的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!