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:
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:
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:
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!