Javascript 未定义/找到XMLHttpRequest模块
这是我的代码:Javascript 未定义/找到XMLHttpRequest模块,javascript,node.js,xmlhttprequest,Javascript,Node.js,Xmlhttprequest,这是我的代码: 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 fin
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浏览器中的内置对象 不随节点分布;你必须
npm install xmlhttprequest
在代码中要求它
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
是一个用于发出HTTP请求的库,该库可用于节点和浏览器,目前非常流行。自从上次更新后,在某些情况下它无法按预期工作 因此,您可以使用。换言之:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
变成:
var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();
但是。。。当然,还有更流行的模块,例如,因为使用承诺:
// 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);
});
使用,您可以从JS代码全局覆盖XMLHttpRequest
。这允许您在节点中使用打算从浏览器运行的外部库/假定它们在浏览器中运行
global.XMLHttpRequest=require('xhr2');
“xmlhttprequest”对我不起作用。我不得不使用下面帖子中的“xhr2”来使我的脚本正常工作。脚本与最新的Google Chrome兼容-将响应加载为ArrayBuffer:“xhr.responseType='ArrayBuffer'