duan19913 2019-07-02 18:09
浏览 283
已采纳

自定义HTTP标头打破了CORS

My API has following CORS setup:
(I am the owner, I can change these settings)

Middleware function:

// 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)
    })
}

The X-APIKEY header is not necessary yet, a request without it just works fine:

fetch('http://localhost:8013/tobi@gmx.at/usage', { headers: { } })
.then(response => response.json())
.then(console.log)

returns {used: false} (expected response)

However, if I add the X-APIKEY header:

fetch('http://localhost:8013/tobi@gmx.at/usage', { headers: { 'X-APIKEY': 'sdfsdfsafsf' } })
.then(response => response.json())
.then(console.log)

following error is thrown:
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.

If I do the request with the X-APIKEY header in Postman, it says that the Access-Control-Allow-Origin header is sent along: Postman says the header is sent along

P.S.: I already tried other headers, it works! If I do the request with chrome (without X-APIKEY header), the Access-Control-Allow-Origin header is sent.

Thanks for your help!

  • 写回答

1条回答 默认 最新

  • 普通网友 2019-07-05 17:57
    关注

    I've now fixed it like this:
    I misuse the http Accept header for my API-Token.

    Example:

    fetch('http://10.0.0.11:8013/lopm@htl/usage',
    {"headers":{ "Accept": "fdfdsf5df6d541cd6++" }})
    .then(response => response.json())
    .then(console.log)
    


    Of course, this isn't a really nice solution, but it does its job.

    Thanks for all of you for giving me helpful tips!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含