我的API具有以下CORS設(shè)置:(我是所有者,我可以更改這些設(shè)置)中間件功能:// HeaderMiddleware ...func HeaderMiddleware(next httprouter.Handle) httprouter.Handle { return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-APIKEY") // ! Production // if r.Header.Get("X-APIKEY") != "fdfdsf5df6d541cd6" || r.RemoteAddr != frontendURL { // w.WriteHeader(http.StatusForbidden) // json.NewEncoder(w).Encode(NoContentResponse{Success: false, Error: "You aren't allowed to request the api here."}) // return // } // ! Production next(w, r, p) })}X-APIKEY 標(biāo)頭還不是必需的,沒(méi)有它的請(qǐng)求也可以正常工作:fetch('http://localhost:8013/tobi@gmx.at/usage', { headers: { } }).then(response => response.json()).then(console.log)返回{used: false}(預(yù)期響應(yīng))但是,如果我添加 X-APIKEY 標(biāo)頭:fetch('http://localhost:8013/tobi@gmx.at/usage', { headers: { 'X-APIKEY': 'sdfsdfsafsf' } }).then(response => response.json()).then(console.log)拋出以下錯(cuò)誤:Access to fetch at 'http://localhost:8013/tobiwibu@gmx.at/usage' from origin 'http://localhost:8080' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.如果我在 Postman 中使用 X-APIKEY 標(biāo)頭執(zhí)行請(qǐng)求,它表示 Access-Control-Allow-Origin 標(biāo)頭已一起發(fā)送: PS: 我已經(jīng)嘗試過(guò)其他標(biāo)頭,它有效!如果我使用 chrome 發(fā)出請(qǐng)求(沒(méi)有 X-APIKEY 標(biāo)頭),則會(huì)發(fā)送 Access-Control-Allow-Origin 標(biāo)頭。 感謝您的幫助!
1 回答

BIG陽(yáng)
TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
我現(xiàn)在已經(jīng)像這樣修復(fù)了它:
我誤用了我的 API 令牌的 http Accept 標(biāo)頭。
例子:
fetch('http://10.0.0.11:8013/lopm@htl/usage',
{"headers":{ "Accept": "fdfdsf5df6d541cd6++" }})
.then(response => response.json())
.then(console.log)
當(dāng)然,這并不是一個(gè)很好的解決方案,但它確實(shí)起到了作用。
感謝大家給我有用的建議!
- 1 回答
- 0 關(guān)注
- 183 瀏覽
添加回答
舉報(bào)
0/150
提交
取消