How to Use XMLHttpRequest with Node.js (Code Examples)

Posted December 20, 2023
How to Use XMLHttpRequest with Node.js (Code Examples)

XMLHttpRequest makes sure you can get data without a full page refresh on the browser. XMLHttpRequest is a browser API and is not available in Node.js runtime. It uses an XMLHttpRequest object so web browsers can make HTTP requests from client-side JavaScript.

Related: How to Render HTML and CSS Pages With Node.js MySQL Server

XMLHttpRequest with Node.js

Node.js uses the http or https modules to make HTTP requests. Back in the day, Node.js used node-XMLHttpRequest module as a wrapper to emulate the browser XMLHttpRequest object for GET, POST, PUT, and DELETE requests.

The node-XMLHttpRequest worked as follows when using Node.js:

  • You Install the XMLHttpRequest package:
npm install xmlhttprequest
  • Create your example API using XMLHttpRequest library and Node.js:
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

const url = "https://jsonplaceholder.typicode.com/todos/1";

const xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      console.log(xhr.responseText);
    } else {
      console.error(`Request failed with status ${xhr.status}`);
    }
  }
};

xhr.open("GET", url, true);
xhr.send();

Why XMLHttpRequest with Node.js is a Bad Idea

The bad thing is that using XMLHttpRequest in Node.js is not a common practice. The node-XMLHttpRequest hasn’t been updated for more than 8 years. node-XMLHttpRequest is therefore irreverent and you won’t be able to use it in the modern Node.js ecosystem.

Enters xhr2 XMLHttpRequest Emulation

xhr2 works the same as XMLHttpRequest. There is not much difference between them.

If you check the following Example using the xhr2 library in Node.js, they both have the same code structure, and nothing new is added:

// Example using xhr2 library in Node.js

const XMLHttpRequest = require("xhr2");

const url = "https://jsonplaceholder.typicode.com/todos/1";

const xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      console.log(xhr.responseText);
    } else {
      console.error(`Request failed with status ${xhr.status}`);
    }
  }
};

xhr.open("GET", url, true);
xhr.send();

Should you use XMLHttpRequest Module with Node.js

XMLHttpRequest and Node.js? Well, here are the reasons I wouldn’t use XMLHttpRequest Module with Node.js:

  • XMLHttpRequest is a client-side API for web browsers. This means it is not a part of the Node.js runtime. We all know Node.js as a server-side JavaScript runtime.
  • If you are using XMLHttpRequest, Node.js features such as asynchronous and event-driven architecture are thrown out of the window. XMLHttpRequest is event-driven with a callback-based design.
  • Picture yourself creating a Node.js app with XMLHttpRequest. You will run out of key functionalities and no one wants to create them from scratch while the ecosystem has everything you need.
  • You Don’t get an actively maintained code base and you are open to compatibilities or at least re-writing of your client-side code.
  • If you chose to use XMLHttpRequest, how will you manage Node.js CORS? XMLHttpRequest is subjective when using the same-origin policy. You cannot make requests to a different domain (Origin).

Is there Hope? The Future Node.js XMLHttpRequest

If you want to make HTTP requests with a similar syntax as XMLHttpRequest, you have plenty of options with up-to-date and rich ecosystem compatibility. You don’t need an XHR or XMLHttpRequest:

  • Axios library works both in browsers and in Node.js.
const axios = require('axios');

// Example GET request
axios.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => {
    console.log('GET Request Response:', response.data);
  })
  .catch(error => {
    console.error('GET Request Error:', error.message);
  });

// Example POST request
axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'New post',
    body: 'The New Post Content',
    userId: 1
  })
  .then(response => {
    console.log('POST Request Response:', response.data);
  })
  .catch(error => {
    console.error('POST Request Error:', error.message);
  });

Axios is a modern alternative with similar functionality to perform HTTP requests from the server side:

// src/controllers/todoController.js
const axios = require('axios');

const API_URL = 'https://jsonplaceholder.typicode.com/todos';

exports.getAllTodos = async (req, res) => {
  try {
    const response = await axios.get(API_URL);
    res.json(response.data);
  } catch (error) {
    console.error(error.message);
    res.status(500).json({ message: 'Internal Server Error' });
  }
};
  • It’s then better to use Node.js native modules like http and https, or Express.
// src/server.js
const express = require('express');
const app = express();
const PORT = 3000;

const todoController = require('./controllers/todoController');

app.get('/todos', todoController.getAllTodos);

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Conclusion

Have you learned something? You don’t get XMLHttpRequest with Node.js by default anymore. I hope this post will let decide the best alternative path if you still want to achieve the functionalities of XMLHttpRequest within Node.js.

How to Use XMLHttpRequest with Node.js (Code Examples)

Written By:

Joseph Chege