目錄
問題內容
版本
問題
程式碼
案例3
從航廈起飛
502 Bad Gateway
已解決
解決方法
首頁 後端開發 Golang 無法從主網域存取子網域:沒有'Access-Control-Allow-Origin”

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

Feb 09, 2024 pm 06:30 PM

無法從主網域存取子網域:沒有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 id="Bad-Gateway">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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Debian OpenSSL有哪些漏洞 Debian OpenSSL有哪些漏洞 Apr 02, 2025 am 07:30 AM

OpenSSL,作為廣泛應用於安全通信的開源庫,提供了加密算法、密鑰和證書管理等功能。然而,其歷史版本中存在一些已知安全漏洞,其中一些危害極大。本文將重點介紹Debian系統中OpenSSL的常見漏洞及應對措施。 DebianOpenSSL已知漏洞:OpenSSL曾出現過多個嚴重漏洞,例如:心臟出血漏洞(CVE-2014-0160):該漏洞影響OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻擊者可利用此漏洞未經授權讀取服務器上的敏感信息,包括加密密鑰等。

Go語言中用於浮點數運算的庫有哪些? Go語言中用於浮點數運算的庫有哪些? Apr 02, 2025 pm 02:06 PM

Go語言中用於浮點數運算的庫介紹在Go語言(也稱為Golang)中,進行浮點數的加減乘除運算時,如何確保精度是�...

Go的爬蟲Colly中Queue線程的問題是什麼? Go的爬蟲Colly中Queue線程的問題是什麼? Apr 02, 2025 pm 02:09 PM

Go爬蟲Colly中的Queue線程問題探討在使用Go語言的Colly爬蟲庫時,開發者常常會遇到關於線程和請求隊列的問題。 �...

從前端轉型後端開發,學習Java還是Golang更有前景? 從前端轉型後端開發,學習Java還是Golang更有前景? Apr 02, 2025 am 09:12 AM

後端學習路徑:從前端轉型到後端的探索之旅作為一名從前端開發轉型的後端初學者,你已經有了nodejs的基礎,...

在 Go 語言中,為什麼使用 Println 和 string() 函數打印字符串會出現不同的效果? 在 Go 語言中,為什麼使用 Println 和 string() 函數打印字符串會出現不同的效果? Apr 02, 2025 pm 02:03 PM

Go語言中字符串打印的區別:使用Println與string()函數的效果差異在Go...

Debian下PostgreSQL監控方法 Debian下PostgreSQL監控方法 Apr 02, 2025 am 07:27 AM

本文介紹在Debian系統下監控PostgreSQL數據庫的多種方法和工具,助您全面掌握數據庫性能監控。一、利用PostgreSQL內置監控視圖PostgreSQL自身提供多個視圖用於監控數據庫活動:pg_stat_activity:實時展現數據庫活動,包括連接、查詢和事務等信息。 pg_stat_replication:監控複製狀態,尤其適用於流複製集群。 pg_stat_database:提供數據庫統計信息,例如數據庫大小、事務提交/回滾次數等關鍵指標。二、借助日誌分析工具pgBadg

Beego ORM中如何指定模型關聯的數據庫? Beego ORM中如何指定模型關聯的數據庫? Apr 02, 2025 pm 03:54 PM

在BeegoORM框架下,如何指定模型關聯的數據庫?許多Beego項目需要同時操作多個數據庫。當使用Beego...

在Go語言中使用Redis Stream實現消息隊列時,如何解決user_id類型轉換問題? 在Go語言中使用Redis Stream實現消息隊列時,如何解決user_id類型轉換問題? Apr 02, 2025 pm 04:54 PM

Go語言中使用RedisStream實現消息隊列時類型轉換問題在使用Go語言與Redis...

See all articles