How to make a HTTPS POST in Node.js without any third party module?

Sometimes, we want to make a HTTPS POST in Node.js without any third party module.

In this article, we’ll look at how to make a HTTPS POST in Node.js without any third party module.

How to make a HTTPS POST in Node.js without any third party module?

To make a HTTPS POST in Node.js without any third party module, we can use the https.request method.

For instance, we write

const https = require('https');

const postData = JSON.stringify({
  'msg': 'Hello World!'
});

const options = {
  hostname: 'jsonplaceholder.com',
  port: 443,
  path: '/post',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': postData.length
  }
};

const req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

to call https.request with the options for the request, which includes the request URL, method, and headers.

We get the response from the callback we pass into https.request as the 2nd argument.

And we pass in the request body by calling the req.write.

res.on lets us listen to the response by listening to the 'data' event.

And the 'error' event is emitted when there’s an error.

Conclusion

To make a HTTPS POST in Node.js without any third party module, we can use the https.request method.