简体   繁体   中英

XMLHttpRequest module not defined/found

This is my code:

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

I am getting the error:

Cannot find module 'xmlhttprequest'

When I remove the first line, I am getting:

XMLHttpRequest is not defined

I have searched all over and people have mentioned a problem with Node.js here and there but my installation of Node was correct so I'm not sure what the issue is.

XMLHttpRequest is a built-in object in web browsers .

It is not distributed with Node; you have to install it separately ,

  1. Install it with npm,

     npm install xmlhttprequest
  2. Now you can require it in your code.

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

That said, the http module is the built-in tool for making HTTP requests from Node.

Axios is a library for making HTTP requests which is available for Node and browsers that is very popular these days.

Since the last update of the xmlhttprequest module was around 2 years ago , in some cases it does not work as expected.

So instead, you can use the xhr2 module . In other words:

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

becomes:

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

But ... of course, there are more popular modules like Axios , because -for example- uses 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);
});

With the xhr2 library you can globally overwrite XMLHttpRequest from your JS code. This allows you to use external libraries in node, that were intended to be run from browsers / assume they are run in a browser.

global.XMLHttpRequest = require('xhr2');

Just go to the terminal install xmlhttprequest by following code

Install it with npm,

  1. npm install xmlhttprequest

  2. Now you can require it in your code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM