/

Making HTTP requests with Node.js

Making HTTP requests with Node.js

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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