HTTP POST request with Node.js


Uncategorized March 3, 2023 admin 4291

To make an HTTP POST request with Node.js and send JSON data in the request body, you can use the built-in http or https module. Here’s an example using the http module:

const http = require(‘http’);

const data = JSON.stringify({
name: ‘John Doe’,
email: ‘johndoe@example.com’
});

const options = {
hostname: ‘api.example.com’,
path: ‘/users’,
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
‘Content-Length’: data.length
}
};

const req = http.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 create a JSON object containing some user data, and then use the JSON.stringify() method to convert it to a string. We set the necessary options for the request, including the HTTP method (POST), the request path (/users), and the headers that specify the content type and length of the request body.

We then create an HTTP request using the http.request() method, passing in the options we defined. We listen for the response event on the request object, and log the response status code to the console. We also listen for the data event on the response object, and write the response data to the console.

Finally, we call the req.write() method to write the request body data to the request, and then call req.end() to send the request.

Movie Request

Leave a Message

Registration isn't required. By commenting you accept the Privacy Policy