How to POST data with request module on Node.js?

Sometimes, we want to POST data with request module on Node.js.

In this article, we’ll look at how to POST data with request module on Node.js.

How to POST data with request module on Node.js?

To POST data with request module on Node.js, we can use the request.post method.

For instance, we write

const request = require('request');
request.post({
  headers: {
    'content-type': 'application/x-www-form-urlencoded'
  },
  url: 'http://localhost/test2.php',
  body: "mes=heydude"
}, (error, response, body) => {
  console.log(body);
});

to call request.post with an object that has the request headers, url, and request body.

The callback in the 2nd argument runs when the request is finished.

We get the response body from body.

Conclusion

To POST data with request module on Node.js, we can use the request.post method.