/

How to Make an HTTP POST Request using Node

How to Make an HTTP POST Request using Node

Learn how to make an HTTP POST request using Node.js. There are multiple options available, depending on the level of abstraction you prefer.

The simplest way to perform an HTTP POST request in Node.js is by using the Axios library. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
const axios = require('axios');

axios.post('/todos', {
todo: 'Buy the milk',
})
.then((res) => {
console.log(`statusCode: ${res.statusCode}`);
console.log(res);
})
.catch((error) => {
console.error(error);
});

Another option is to use the Request library. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const request = require('request');

request.post('/todos', {
json: {
todo: 'Buy the milk',
},
}, (error, res, body) => {
if (error) {
console.error(error);
return;
}
console.log(`statusCode: ${res.statusCode}`);
console.log(body);
});

Both of these methods require the use of a third-party library. However, it is also possible to make a POST request using only the Node.js standard modules, although it is more verbose. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const https = require('https');

const data = JSON.stringify({
todo: 'Buy the milk',
});

const options = {
hostname: 'yourwebsite.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length,
},
};

const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);

res.on('data', (d) => {
process.stdout.write(d);
});
});

req.on('error', (error) => {
console.error(error);
});

req.write(data);
req.end();

Choose the method that best suits your needs and start making HTTP POST requests in Node.js today!

tags: [“Node.js”, “HTTP POST request”, “Axios”, “Request library”, “third-party library”, “standard modules”]