亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

自定義 http 標頭破壞 CORS

自定義 http 標頭破壞 CORS

Go
慕妹3146593 2023-06-26 18:03:54
我的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)


當然,這并不是一個很好的解決方案,但它確實起到了作用。


感謝大家給我有用的建議!


查看完整回答
反對 回復 2023-06-26
  • 1 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號