Not able to make node js post request? In this guide, you will learn how to make a successful node.js HTTP post request.

What is a ‘POST’ Request?

‘POST’ request is one of the most used HTTP requests. If you have any data to send to a server, we usually make a ‘POST’ request.

The data can be web form data, file uploads, or any sensitive data. These data can be found in the body of the request message.

‘POST’ request differs from ‘GET’ request as the data is not sent using the URL parameter. Consequently, the data is sent using send() function.

Node JS Post Request Example

let XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

let url = '';
//let apiKey = 'your api';

let data = JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1, });

let object =  new XMLHttpRequest();'POST',url);


object.onreadystatechange = function (){


Successful post request response on console

handle post request node js

How to make a post request in node.js

8 Steps to Make Node JS Post Request

1. Add xmlhttprequest to your node package using the command: npm i xmlhttprequest

2. Use xmlhttprequest in your node project as below:

let XMLHttpRequest=require('xmlhttprequest').XMLHttpRequest;

3.You must have an API URL, an API key (optional) and data that needs to be sent.

let url = 'API Link url';
let apiKey = 'your api key';
let data = JSON.stringify({depends on your api what it accepts});

Note: Data should be in the string format, above we have changed the object to a string using JSON.stringify().

4. Create an object/instance of XMLHttpRequest() class.

let xhr = new XMLHttpRequest();

5. Open the request by using open() function with the help of the object. The open() function needs two parameters. The first parameter accepts request type i.e ‘POST’ and the second parameter the API URL.'POST',url);

6. Next, use the object to set the request header as Content-Type to application/json.


This is optional, if you have the API key then you need to set the request header apikey: ‘your api key’ to your api key.


7. Use the object to check readyState attribute. Whenever readyState value changes a callback function is called. The onreadystatechange contains the event handler and fires every time the value of readyStage changes.

So, if readyState value becomes 4 which means status is DONE. We finally, console.log the responseText.

xhr.onreadystatechange = function (){

8. Finally, you pass the data to the send() function.


After the node program is done, run it by typing node app.js in the terminal.
Check the successful response from the server on the console if not then check for any errors, failures or rejections.

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed