Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create an HTTP POST request using node.js, you can use the built-in http or https module. Here is an example code snippet:

const https = require('https');

const data = JSON.stringify({
  message: 'Hello World!',
});

const options = {
  hostname: 'example.com',
  port: 443,
  path: '/api/messages',
  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();

In this example, we are making an HTTPS POST request to example.com/api/messages with a JSON payload of { message: 'Hello World!' }. The request headers include the Content-Type and Content-Length fields. The response from the server is logged to the console.