Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/477.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 自定义http头断开CORS_Javascript_Http_Go_Cors_Fetch - Fatal编程技术网

Javascript 自定义http头断开CORS

Javascript 自定义http头断开CORS,javascript,http,go,cors,fetch,Javascript,Http,Go,Cors,Fetch,My API具有以下CORS设置: 我是所有者,我可以更改这些设置 中间件功能: //头端软件。。。 func HeaderMiddlewarenext httprouter.Handle httprouter.Handle{ 返回httprouter.Handlefuncw http.ResponseWriter,r*http.Request,p httprouter.Params{ w、 Header.SetContent-Type,application/json w、 Header.Se

My API具有以下CORS设置: 我是所有者,我可以更改这些设置 中间件功能:

//头端软件。。。 func HeaderMiddlewarenext httprouter.Handle httprouter.Handle{ 返回httprouter.Handlefuncw http.ResponseWriter,r*http.Request,p httprouter.Params{ w、 Header.SetContent-Type,application/json w、 Header.SetAccess-Control-Allow-Origin* w、 Header.SetAccess-Control-Allow-Headers,来源,X-request-With,内容类型,接受,X-APIKEY //!制作 //如果r.Header.GetX-APIKEY!=fdfdsf5df6d541cd6 | | r.RemoteAddr!=frontendURL{ //w.WriteHeaderhttp.Status禁止 //json.NewEncoderw.EncodeNoContentResponse{Success:false,Error:不允许您在此处请求api。} //返回 // } //!制作 下一个 } } 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)
引发以下错误: 在'http://localhost:8013/tobiwibu@gmx.at/用法“从原产地”http://localhost:8080'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在'access control Allow Origin'标头。如果不透明响应满足您的需要,请将请求的模式设置为“no cors”,以获取禁用cors的资源。 如果我在Postman中使用X-APIKEY头执行请求,它会说Access Control Allow Origin头随附发送: 附言:我已经试过其他标题了,很有效! 如果我使用不带X-APIKEY头的chrome执行请求,则会发送Access Control Allow Origin头。
谢谢你的帮助

我现在这样修复它: 我滥用了API令牌的http Accept头。 例如:

当然,这不是一个很好的解决方案,但它确实起到了作用。
谢谢你们给我有用的建议

似乎有一些应用程序逻辑会查看X-APIKEY,并跳过基于该逻辑在响应上设置Access Control Allow Origin。在没有看到相关代码的情况下,我们无法知道。我只是添加了整个中间件功能。100%确定它在测试前后都会被称为“打印测试”。我希望这就是你的意思。添加自定义标题意味着浏览器在发送GET之前发出选项动词请求。您的服务器可能没有响应选项。
fetch('http://10.0.0.11:8013/lopm@htl/usage',
{"headers":{ "Accept": "fdfdsf5df6d541cd6++" }})
.then(response => response.json())
.then(console.log)