XMLHttpRequest 模块不是 defined/found

XMLHttpRequest module not defined/found

这是我的代码:

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 安装是正确的,所以我不确定问题是什么。

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

它没有随 Node.js 一起发布。 The http module 是从 Node 发出 HTTP 请求的内置工具。

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

2022 更新:节点 18 具有 fetch enabled by default.

的本机实现

如果您真的想在 Node.js 中使用 XHR,那么有几个第三方实现。 xmlhttprequest (which seems to be unmaintained) and xhr2(今年有更新)。

  1. 用npm安装,

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

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

自上次更新 xmlhttprequest module was around 2 years ago 以来,在某些情况下它无法按预期工作。

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

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

变为:

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

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

// 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);
});

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

global.XMLHttpRequest = require('xhr2');