CORS 策略:對預檢請求的回應未通過存取控制檢查:無'Access-Control-Allow-Origin”
我在後端使用 golang 和 gin-gonic/gin web 框架,在前端使用 react axios。我已經嘗試解決它兩天了,但我仍然遇到以下相同的錯誤:
cors policy: response to preflight request doesn't pass access control check: no 'access-control-allow-origin' header is present on the requested resource.
僅當我嘗試發送 patch 請求時才會發生此錯誤,因此該請求需要預檢 options 請求,但 get 和 post 一切都按預期工作,它們不運行任何預檢檢查。
這是我的路由器設定的程式碼:
package main import ( "book_renting/api" "log" "net/http" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" "github.com/gin-gonic/contrib/cors" "github.com/gin-gonic/gin" _ "github.com/lib/pq" ) func main() { router := gin.default() store := cookie.newstore([]byte("your-secret-key")) store.options(sessions.options{maxage: 60 * 60 * 24}) router.use(cors.default()) router.use(sessions.sessions("sessions", store)) router.use(func(c *gin.context) { host := c.request.header.get("origin") c.writer.header().set("access-control-allow-origin", host) c.writer.header().set("access-control-allow-credentials", "true") c.writer.header().set("access-control-allow-headers", "content-type, authorization") c.writer.header().set("access-control-allow-methods", "get, post, put, delete, patch, options") if c.request.method == "options" { log.println("handling options request") c.abortwithstatus(http.statusnocontent) return } log.println("executing cors middleware") c.next() }) router.post("/login", api.handlelogin) router.get("/logout", api.handlelogout) router.post("/register", api.handleregister) router.get("/getcookie", api.getcookiesession) router.get("/books", api.getbooksapi) router.get("/books/:id", api.bookbyidapi) router.patch("/rent/:id", api.rentbookapi) router.patch("/return/:id", api.returnbookapi) router.run("localhost:3000") }
這是前端:
import axios from 'axios' const url = 'http://localhost:3000' export const loginuser = async (credentials) => await axios.post(`${url}/login`, credentials, {withcredentials: true}) export const logoutuser = async () => await axios.get(`${url}/logout`, {withcredentials: true}) export const registeruser = () => axios.post(`${url}/register`) export const fetchbooks = () => axios.get(`${url}/books`, { withcredentials: true }) export const fetchbookbyid = (book_id) => axios.get(`${url}/books/${book_id}`, { withcredentials: true }) export const rentbook = (book_id) => axios.patch(`${url}/rent/${book_id}`, { withcredentials: true }) export const returnbook = (book_id) => axios.patch(`${url}/return/${book_id}`, { withcredentials: true })
我非常確定我正確設定了後端,它應該會傳回所有必要的標頭。
例如,對於 get 請求,回應標頭如下所示:
http/1.1 200 ok access-control-allow-credentials: true access-control-allow-headers: content-type, authorization access-control-allow-methods: get, post, put, delete, patch, options access-control-allow-origin: http://localhost:3001 content-type: application/json; charset=utf-8 date: sat, 10 jun 2023 22:12:11 gmt content-length: 495
雖然對於 patch 請求嘗試,我沒有任何回應(毫不奇怪),並且預檢回應標頭是:
http/1.1 200 ok date: sat, 10 jun 2023 22:12:12 gmt content-length: 0
您對可能出現的問題有什麼建議嗎?經過這兩天我已經毫無頭緒了。預先感謝您!
我還嘗試新增標題:
c.writer.header().set("access-control-allow-origin", host) c.writer.header().set("access-control-allow-credentials", "true") c.writer.header().set("access-control-allow-headers", "content-type, authorization") c.writer.header().set("access-control-allow-methods", "get, post, put, delete, patch, options")
...再次在 if 語句中:
if c.request.method == "options" { log.println("handling options request") c.abortwithstatus(http.statusnocontent) return }
但這根本沒有幫助。事實上,這個if語句在執行預檢時並沒有執行,我從控制台知道伺服器正在執行options請求。
[gin] 2023/06/11 - 00:12:13 | 200 | 7.708µs | 127.0.0.1 | options "/rent/2"
編輯:
這是發送 patch 請求的 curl 命令(因此實際上這是預檢 options 請求):
curl 'http://localhost:3000/return/2' \ -x 'options' \ -h 'accept: */*' \ -h 'accept-language: en-us,en;q=0.9,pl-pl;q=0.8,pl;q=0.7' \ -h 'access-control-request-headers: content-type' \ -h 'access-control-request-method: patch' \ -h 'cache-control: no-cache' \ -h 'connection: keep-alive' \ -h 'origin: http://localhost:3001' \ -h 'pragma: no-cache' \ -h 'referer: http://localhost:3001/' \ -h 'sec-fetch-dest: empty' \ -h 'sec-fetch-mode: cors' \ -h 'sec-fetch-site: same-site' \ -h 'user-agent: mozilla/5.0 (macintosh; intel mac os x 10_15_7) applewebkit/537.36 (khtml, like gecko) chrome/114.0.0.0 safari/537.36' \ --compressed
對此請求的回應:
HTTP/1.1 200 OK Date: Sun, 11 Jun 2023 01:22:57 GMT Content-Length: 0
正確答案
事實證明,您正在使用已棄用的軟體包github.com/gin-gonic/contrib/cors
。您應該使用 github.com/gin-contrib/cors
代替。這是使用 github.com/gin-contrib/cors
的示範設定:
package main import ( "github.com/gin-contrib/cors" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" "github.com/gin-gonic/gin" ) func main() { router := gin.default() config := cors.defaultconfig() config.addallowheaders("authorization") config.allowcredentials = true config.allowallorigins = false // i think you should whitelist a limited origins instead: // config.allowallorigins = []{"xxxx", "xxxx"} config.alloworiginfunc = func(origin string) bool { return true } router.use(cors.new(config)) store := cookie.newstore([]byte("your-secret-key")) store.options(sessions.options{maxage: 60 * 60 * 24}) router.use(sessions.sessions("sessions", store)) // routes below router.run("localhost:3000") }
由於某種原因,patch
請求標頭缺少「cookie」標頭,儘管我使用了 withcredentials
參數。
axios.patch(`${url}/rent/${book_id}`, { withcredentials: true })
這裡 { withcredentials: true }
被視為數據,並且沒有配置。如果你沒有資料發送到伺服器,你應該這樣寫:
axios.patch(`${url}/rent/${book_id}`, null, { withCredentials: true })
以上是CORS 策略:對預檢請求的回應未通過存取控制檢查:無'Access-Control-Allow-Origin”的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

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

Golang在性能和可擴展性方面優於Python。 1)Golang的編譯型特性和高效並發模型使其在高並發場景下表現出色。 2)Python作為解釋型語言,執行速度較慢,但通過工具如Cython可優化性能。

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

goimpactsdevelopmentpositationality throughspeed,效率和模擬性。 1)速度:gocompilesquicklyandrunseff,IdealforlargeProjects.2)效率:效率:ITScomprehenSevestAndardArdardArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增強的Depleflovelmentimency.3)簡單性。

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。Golang以其并发模型和高效性能著称,Python则以简洁语法和丰富库生态系统著称。

Golang和C 在性能上的差異主要體現在內存管理、編譯優化和運行時效率等方面。 1)Golang的垃圾回收機制方便但可能影響性能,2)C 的手動內存管理和編譯器優化在遞歸計算中表現更為高效。

C 更適合需要直接控制硬件資源和高性能優化的場景,而Golang更適合需要快速開發和高並發處理的場景。 1.C 的優勢在於其接近硬件的特性和高度的優化能力,適合遊戲開發等高性能需求。 2.Golang的優勢在於其簡潔的語法和天然的並發支持,適合高並發服務開發。
