Ask Your Question
2

What is the method for creating an HTTP POST request using node.js?

asked 2023-05-02 18:25:30 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-02 18:36:01 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-02 18:25:30 +0000

Seen: 19 times

Last updated: May 02 '23