node http post
Import the required modules: const http = require('http');
Create an options object: const options = { hostname: 'www.example.com', port: 80, path: '/api', method: 'POST', headers: { 'Content-Type': 'application/json' } };
Create a request object: const req = http.request(options, (res) => { let data = '';
// Handle response data res.on('data', (chunk) => { data += chunk; });
// Handle response end res.on('end', () => { console.log(data); }); });
Handle request errors: req.on('error', (error) => { console.error(error); });
Write the request body: const requestBody = JSON.stringify({ key: 'value' });
req.write(requestBody);
- End the request: req.end();