Мой 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.
Если я делаю запрос с заголовком X-APIKEY в Postman, он говорит, что заголовок Access-Control-Allow-Origin отправляется по:
PS: я уже пробовал другие заголовки, все работает!Если я делаю запрос с Chrome (без заголовка X-APIKEY), отправляется заголовок Access-Control-Allow-Origin.
Спасибо за помощь!