XMLHttpRequest模块未定义/找到

wma*_*ash 59 javascript xmlhttprequest node.js

这是我的代码:

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

我收到错误:

Cannot find module 'xmlhttprequest'
Run Code Online (Sandbox Code Playgroud)

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

XMLHttpRequest is not defined
Run Code Online (Sandbox Code Playgroud)

我已经搜遍过各地,人们已经提到Node.js的问题,但我的Node安装是正确的,所以我不确定是什么问题.

Que*_*tin 98

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

它不与Node一起分发; 你必须单独安装,

  1. 用npm安装,

    npm install xmlhttprequest
    
    Run Code Online (Sandbox Code Playgroud)
  2. 现在你可以 require在你的代码中使用它了.

    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var xhr = new XMLHttpRequest();
    
    Run Code Online (Sandbox Code Playgroud)

也就是说,Node附带了http模块,这是从Node发出HTTP请求的常用工具.

  • 'xmlhttprequest' 对我不起作用。我不得不使用下面帖子中的“xhr2”来使我的脚本工作。脚本与最新的 Google Chrome 兼容 - 将响应加载为 ArrayBuffer: " xhr.responseType = 'arraybuffer'; " (2认同)

ype*_*per 13

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

global.XMLHttpRequest = require('xhr2');
Run Code Online (Sandbox Code Playgroud)


rob*_*007 12

由于xmlhttprequest模块的上次更新大约在2年前,因此在某些情况下它无法按预期工作.

因此,您可以使用xhr2模块.换一种说法:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
Run Code Online (Sandbox Code Playgroud)

变为:

var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();
Run Code Online (Sandbox Code Playgroud)

但是......当然,还有像Axios这样的流行模块,因为 - 例如 - 使用承诺:

// 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);
});
Run Code Online (Sandbox Code Playgroud)