我的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/tobi@gmx.at/usage', { headers: { } })
.then(response => response.json())
.then(console.log)
返回{used: false}(预期响应)
但是,如果我添加 X-APIKEY 标头:
fetch('http://localhost:8013/tobi@gmx.at/usage', { headers: { 'X-APIKEY': 'sdfsdfsafsf' } })
.then(response => response.json())
.then(console.log)
抛出以下错误:
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 标头执行请求,它表示 Access-Control-Allow-Origin 标头已一起发送: PS: 我已经尝试过其他标头,它有效!如果我使用 chrome 发出请求(没有 X-APIKEY 标头),则会发送 Access-Control-Allow-Origin 标头。 感谢您的帮助!
BIG阳
相关分类