【问题标题】:XMLHttpRequest module not defined/foundXMLHttpRequest 模块未定义/未找到
【发布时间】:2015-12-12 19:05:54
【问题描述】:

这是我的代码:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.open("GET", "//URL")
xhr.setRequestHeader("Content-Type: application/json", "Authorization: Basic //AuthKey");
xhr.send();

我收到错误:

Cannot find module 'xmlhttprequest'

当我删除第一行时,我得到:

XMLHttpRequest is not defined

我到处搜索,人们到处都提到了 Node.js 的问题,但我的 Node 安装是正确的,所以我不确定问题是什么。

【问题讨论】:

    标签: javascript node.js xmlhttprequest


    【解决方案1】:

    XMLHttpRequest 是网络浏览器中的内置对象。

    它不随 Node.js 一起分发。 The http module 是用于从 Node 发出 HTTP 请求的内置工具。

    大多数从节点发出 HTTP 请求的人都使用具有更友好 API 的第三方库。两个流行的选择是Axios(用于 Node.js 和浏览器)和node-fetch(它实现了浏览器内置的 fetch API,是 XMLhttpRequest 的现代替代品。

    如果你真的想在 Node.js 中使用 XHR,那么有几个第三方实现。 xmlhttprequest(似乎没有维护)和xhr2(今年有更新)。

    1. 用 npm 安装,

       npm install xhr2
      
    2. 现在你可以在你的代码中require它。

       var XMLHttpRequest = require('xhr2');
       var xhr = new XMLHttpRequest();
      

    【讨论】:

      【解决方案2】:

      由于上次更新 xmlhttprequest module 是在 2 years ago 附近,因此在某些情况下它无法按预期工作。

      因此,您可以使用xhr2 module。换句话说:

      var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
      var xhr = new XMLHttpRequest();
      

      变成:

      var XMLHttpRequest = require('xhr2');
      var xhr = new XMLHttpRequest();
      

      但是...当然,还有更流行的模块,例如 Axios,因为 - 例如 - 使用了 Promise:

      // Make a request for a user with a given ID
      axios.get('/user?ID=12345').then(function (response) {
          console.log(response);
      }).catch(function (error) {
          console.log(error);
      });
      

      【讨论】:

        【解决方案3】:

        使用xhr2 library,您可以从您的JS 代码中全局覆盖XMLHttpRequest。这允许您在节点中使用外部库,这些库旨在从浏览器中运行/假设它们在浏览器中运行。

        global.XMLHttpRequest = require('xhr2');
        

        【讨论】:

          猜你喜欢
          • 2012-07-27
          • 2020-06-06
          • 2019-10-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-15
          • 2020-09-28
          • 2020-09-24
          相关资源
          最近更新 更多