Work with our skilled Node developers to accelerate your project and boost its performance.
Hire Node.js DevelopersTo make an outbound HTTP POST request with data in Node.js, you can use the built-in http or https modules or a library like axios or node-fetch for simplicity.
const https = require('https'); const data = JSON.stringify({ title: 'foo', body: 'bar', userId: 1, }); 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 responseBody = ''; res.on('data', (chunk) => { responseBody += chunk; }); res.on('end', () => { console.log('Response:', JSON.parse(responseBody)); }); }); req.on('error', (error) => { console.error(`Error: ${error.message}`); }); // Write data to the request body req.write(data); req.end();
const axios = require('axios'); const data = { title: 'foo', body: 'bar', userId: 1, }; axios.post('https://jsonplaceholder.typicode.com/posts', data) .then((response) => { console.log('Response:', response.data); }) .catch((error) => { console.error('Error:', error.message); });
const fetch = require('node-fetch'); const data = { title: 'foo', body: 'bar', userId: 1, }; fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }) .then((response) => response.json()) .then((data) => { console.log('Response:', data); }) .catch((error) => { console.error('Error:', error.message); });
const request = require('request'); const data = { title: 'foo', body: 'bar', userId: 1, }; const options = { url: 'https://jsonplaceholder.typicode.com/posts', method: 'POST', json: true, body: data, }; request(options, (error, response, body) => { if (error) { console.error('Error:', error); } else { console.log('Response:', body); } });