我的API具有以下CORS設置:(我是所有者,我可以更改這些設置)中間件功能:// 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 標頭還不是必需的,沒有它的請求也可以正常工作:fetch('http://localhost:8013/[email protected]/usage', { headers: { } }).then(response => response.json()).then(console.log)返回{used: false}(預期響應)但是,如果我添加 X-APIKEY 標頭:fetch('http://localhost:8013/[email protected]/usage', { headers: { 'X-APIKEY': 'sdfsdfsafsf' } }).then(response => response.json()).then(console.log)拋出以下錯誤:Access to fetch at 'http://localhost:8013/[email protected]/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 標頭執行請求,它表示 Access-Control-Allow-Origin 標頭已一起發送: PS: 我已經嘗試過其他標頭,它有效!如果我使用 chrome 發出請求(沒有 X-APIKEY 標頭),則會發送 Access-Control-Allow-Origin 標頭。 感謝您的幫助!
1 回答

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