【问题标题】:Javascript CORS GET request blocked or invalidJavascript CORS GET 请求被阻止或无效
【发布时间】: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


【解决方案1】:

您无法从浏览器设置标头,如果目标 url 在您的服务器或您管理的服务器上运行并且该服务器运行 nodejs,您可以使用 cors https://www.npmjs.com/package/cors,但是,如果这是第三方 url 并且它没有'不允许 CORS,那么您应该通过配置从您的服务器到第三方服务器的代理从后端发出请求,这应该可以解决您的问题。

【讨论】:

    【解决方案2】:

    关于 CORS 与 nodejs 的答案很可能是正确的,但我想建议您运行测试以确保您的代码也能正常工作。

    尝试使用 Chrome 并下载允许 CORS 的扩展程序。这样,您将在尝试正确的解决方案之前先测试功能。

    【讨论】:

      【解决方案3】:

      聚会迟到了……

      http://cors-anywhere.herokuapp.com/ 很棒,但是如果您使用 XMLHttpRequest() 和 GET 方法,则不需要它。只需排除您的标头请求...

      var xhr = new XMLHttpRequest();
      xhr.open( "GET", YOURURL );
      //OMIT THESE...
        //xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        //xhr.withCredentials = true;
        //xhr.setRequestHeader( 'Content-Type', _contenttype );
        //xhr.setRequestHeader( 'CrossDomain', 'true' );
      //....
      
      xhr.addEventListener( 'load',  function () {
             xhr.responseJSON = JSON.parse( xhr.responseText );
             alert( xhr.responseJSON);
      });
      
      xhr.onerror = function(e) { 
            alert("Ajax request error");
      };
      
      xhr.send( JSON.stringify({}) );
      

      【讨论】:

        猜你喜欢
        • 2020-10-02
        • 2021-12-17
        • 2018-10-18
        • 2020-08-16
        • 2022-11-01
        • 2020-07-18
        • 2022-01-24
        • 2022-01-14
        • 2020-08-16
        相关资源
        最近更新 更多