In this blog, we will learn how to perform various types of HTTP requests (GET, POST, PUT, DELETE) using Node.js. Please note that throughout this article, we will be using HTTPS instead of HTTP for more secure connections.
Performing a GET Request
To perform a GET request, we can use the built-in https
module in Node.js. Here’s an example code snippet:
const https = require('https');
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'GET'
};
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.end();
Performing a POST Request
To perform a POST request, we can send data along with the request body. Here’s an example code snippet:
const https = require('https');
const data = JSON.stringify({
todo: 'Buy the milk'
});
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
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();
Performing PUT and DELETE Requests
PUT and DELETE requests can be performed using the same POST request format, with just the options.method
value changed accordingly.
Tags: Node.js, HTTP requests, GET request, POST request, PUT request, DELETE request