【发布时间】:2019-09-10 19:36:15
【问题描述】:
我已经为向第 3 方 REST Api 发出简单的 GET 请求而苦苦挣扎了一段时间。我已经阅读了一些教程和 SO 问题,但我无法让它发挥作用。我遇到了两个错误之一
预检响应无效(重定向)
或(如果通过 https)
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'https://localhost:8433'。
关于第二条消息:只是服务器不支持CORS的问题吗?
我的代码:
var xmlHttp = new XMLHttpRequest();
var url = 'https://inspirehep.net/record/451647?of=recjson&ot=recid,number_of_citations,authors,title'; //http or https, tried both
/*
doing sth with response here like populate dropdown etc.
*/
xmlHttp.open('GET', url, true);
xmlHttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type, X-Requested-With, Cache-Control");
xmlHttp.setRequestHeader("Content-Type", "application/json");
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", '*');
xmlHttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
xmlHttp.setRequestHeader("Access-Control-Allow-Credentials", "true");
xmlHttp.send();
整个应用程序在 node.js 服务器 (localhost) 上运行,上面的脚本作为单独的文件包含在 .html 视图中。
我可以正确地从网络浏览器、提琴手、邮递员等获取此 API 的 json 响应。我还尝试了不同的 API(例如 Openweather API),认为这是服务器配置的问题,但结果是一样的。
如果能提供任何帮助,我将不胜感激 - 也许我只是对 CORS 有误解。
【问题讨论】:
-
CORS 标头不是您可以在请求中发送的内容。服务器必须响应标头。
-
"只是服务器不支持CORS的问题吗?" — 是的。
-
感谢您的回答,我认为可能是这种情况。
标签: javascript api cors