Node.js - Errors - ReferenceError: XMLHttpRequest is not defined

Attempting to run the following JavaScript code (an AJAX call using XMLHttpRequest) throws a ReferenceError under Node, but works in a web browser.

Why?

Reproducing the problem

The code sample below uses the browser's XMLHttpRequest object to make an asynchronous HTTP GET request for the file book.json.
This is a standard AJAX call.

To run under Node (and see the error), type:

node test.js

Test.js:

var xhr = new XMLHttpRequest();
xhr.open("GET", "/demo/book.json");
 
xhr.onreadystatechange = function () {
    console.log("readyState = " + this.readyState + ", status = " + this.status);
    if (this.readyState == 4 && this.status == 200) {
        var result = this.responseText;
        console.log(result);
    }
};
 
xhr.send();
var xhr = new XMLHttpRequest();
              ^
 
ReferenceError: XMLHttpRequest is not defined
 

Explanation

The XMLHttpRequest type is natively supported in web browsers only.
It is not part of Node, but it can be installed as a package using npm.

The fix

1) Install xmlhttprequest using npm.

npm install xmlhttprequest --save

2) Add require("xmlhttprequest").

The code will now work under node.

Only the first line is new. The rest is the same.

Test.js (updated):

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
 
var xhr = new XMLHttpRequest();
xhr.open("GET", "/demo/book.json");
 
xhr.onreadystatechange = function () {
    console.log("readyState = " + this.readyState + ", status = " + this.status);
    if (this.readyState == 4 && this.status == 200) {
        var result = this.responseText;
        console.log(result);
    }
};
 
xhr.send();

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath