How to create different post request using Node.js ?
Last Updated :
25 Dec, 2020
A POST request is one of the important requests in all HTTP requests. This request is used for storing the data on the WebServer. For Eg File uploading is a common example of a post request. There are many approached to perform an HTTP POST request in Node.js. Various open-source libraries are also available for performing any kind of HTTP request.
There are three approaches to create different post requests are discussed below.
- Using Needle Module
- Using axiom Module
- Using https Module
Below all three approaches all discussed in detail:
Approach 1: One of the ways of making an HTTP POST request in Node.js is by using the Needle library. Needle is a HTTP client for making HTTP requests in Node.js , multipart form-data (e.g. file uploads) , automatic XML & JSON parsing etc.
Project structure:
Installing module:
npm install needle
Index.js
Javascript
const needle = require( 'needle' );
const data = {
name: 'geeksforgeeks' ,
job: 'Content Writer' ,
topic: 'Node.js'
};
data, {json: true })
.then((res) => {
console.log( 'Body: ' , res.body);
}). catch ((err) => {
console.error(err.Message);
}
);
|
Execution command:
node index.js
Console Output:
Approach 2: Another library that can be used is Axios. This is a popular node.js module used to perform HTTP requests and supports all the latest browsers. It also supports async/await syntax for performing a POST request.
Installing module:
npm install axios
Index.js
Javascript
const axios = require( 'axios' );
const data = {
name: 'geeksforgeeks' ,
job: 'Content Writer' ,
topic: 'Node.js'
};
const addUser = async () => {
try {
const res = await axios.post(
console.log( 'Body: ' , res.data);
} catch (err) {
console.error(err.Message);
}
};
|
Execution command:
node index.js
Console Output:
Approach 3: It is also possible to perform a POST request using Node.js built-in HTTPS module. This module is used for sending the data in an encrypted format
Index.js
Javascript
const https = require( 'https' );
const data = JSON.stringify({
name: 'geeksforgeeks' ,
job: 'Content Writer' ,
topic: 'Node.js'
});
const options = {
hostname: 'reqres.in' ,
path: '/api/users' ,
method: 'POST'
};
const req = https.request(options, (res) => {
let data = '' ;
res.on( 'data' , (chunk) => {
data += chunk;
});
res.on( 'end' , () => {
console.log( 'Body:' , JSON.parse(data));
});
}).on( "error" , (err) => {
console.log( "Error: " , err.message);
});
req.write(data);
req.end();
|
Execution command:
node index.js
Console output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...