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

Attempting to run the following Ajax code (using XMLHttpRequest) produces an error in Node, but works in a web browser.

Why?

Running from Node:

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.

npm install xmlhttprequest --save

The first line is new. The rest of the code is the same.

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