javascript - 自定义 http header 破坏 CORS

标签 javascript http go cors fetch

我的 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 header 还不是必需的,没有它的请求也可以正常工作:

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

返回 {used: false}(预期响应)

但是,如果我添加 X-APIKEY header :

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

抛出以下错误:
从来源“http://localhost:8080”获取“http://localhost:8013/tobiwibu@gmx.at/usage”的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

如果我在 Postman 中使用 X-APIKEY header 发出请求,它会说 Access-Control-Allow-Origin header 是一起发送的: Postman says the header is sent along

P.S.:我已经尝试过其他标题,它有效! 如果我使用 chrome(没有 X-APIKEY header )执行请求,则会发送 Access-Control-Allow-Origin header 。

感谢您的帮助!

最佳答案

我现在已经修复了它:
我滥用了 API-Token 的 http Accept header 。

示例:

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


当然,这不是一个很好的解决方案,但它确实起到了作用。

感谢大家给我有用的提示!

关于javascript - 自定义 http header 破坏 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56858003/

相关文章:

javascript - 修改函数输出 - 检查源 - Javascript - HTML - Google Chrome

javascript - JS 将未定义值转为空字符串

JavaScript 正则表达式 : validate date time

javascript - JS 正则表达式 : exec(): "merge" different groups to the same result

python - 将字节对象列表转换为字典

javascript - 无法读取 Set-Cookie 响应 header

javascript - 使用 postMessage 跨域消息传递

arrays - Go - 使用序列从 URL 下载文件

go - 在 golang 中,Time.Format() 从小数部分删除尾随零

c - Go cgo ldap_init 无法确定 C.ldap_init 的名称类型