Use the https module or third-party tools like axios for POST requests. They help you send data to APIs with headers and payloads.
Problem
Making HTTP POST requests is a basic thing to do when building APIs, web applications, and microservices in Node.js. A lot of people have a hard time choosing the right way or package.
Solution
There are many ways to make HTTP POST requests in Node.js:
Example 1: https Module
const https = require(‘https’);const data = JSON.stringify({ name: ‘eSparkBiz’ });
const options = {
hostname: ‘jsonplaceholder.typicode.com’,
path: ‘/posts’,
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
‘Content-Length’: data.length
}
};
const req = https.request(options, res => {
let body = ”;
res.on(‘data’, chunk => { body += chunk; });
res.on(‘end’, () => {
console.log(‘Response:’, body);
});
});
req.on(‘error’, error => {
console.error(‘Error:’, error);
});
req.write(data);
req.end();
Also Read: Top Node.js Interview Questions to Ask Before Hiring a Node.js Developer
Example 2: Axios library
const axios = require(‘axios’);axios.post(‘https://jsonplaceholder.typicode.com/posts’, {
name: ‘eSparkBiz’
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
Example 3: Fetch()
const response = await fetch(‘https://jsonplaceholder.typicode.com/posts’, {method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ name: ‘eSparkBiz’ })
});
const result = await response.json();
console.log(result);
Also Read: Could Not Determine jupyterlab Build Status Without Node JS
Key Takeaways
There are many ways you can send POST request in Node.js. You can either use axios or fetch() for ease and readability. Native https is most powerful but more lengthy.