XMLHttpRequest模块未定义/find

这是我的代码:

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在这里和那里的问题,但我的安装节点是正确的,所以我不知道是什么问题。

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

它不与Node分发; 你必须使用npm 单独安装 。

也就是说,Node附带了http模块 ,它是从Node进行HTTP请求的常用工具。

由于xmlhttprequest模块的上次更新大约在2年前 ,在某些情况下,它不能按预期工作。

相反,你可以使用xhr2模块 。 换一种说法:

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

变为:

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

但是…当然,还有更多stream行的模块,比如说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); });