Bobcares

HTTP Client in Node.js – How to create with Core HTTP

by | Mar 6, 2021

Need help to create HTTP Client in Node.js? We can help you.

Modern web applications communicate with other servers to accomplish tasks. Similarly, in a Node.js app, we can communicate with web APIs by making HTTP requests.

As part of our Server Management Services, we assist our customers with several Node.js queries.

Today, let us see how to create HTTP Client in Node.js with Core HTTP.

 

HTTP Client in Node.js

In order to begin, our Support Techs suggest installing Node.js, and the methods to send HTTP requests to have a Stream-based API. Moving ahead, let us see the steps to create HTTP Client in Node.js.

Step 1 – Make a GET Request

We typically make GET requests to retrieve data from web servers. The code will retrieve a JSON array of user-profiles from a publicly accessible API.

The HTTPS module has two functions to make GET requests – the get() function, which can only make GET requests, and the request() function, which makes other types of requests. You will begin by making a request with the get() function.

  • Making Requests with get()
https.get(URL_String, Callback_Function) {
Action
}

First, we set up the coding environment. Create a folder to store all the Node.js modules:

$ mkdir requests

Enter the folder:

$ cd requests

Then create and open a new file in a text editor.

$ nano getRequestWithGet.js

To make HTTP requests in Node.js, import the HTTPS module by adding the following line:

const https = require(‘https’);

Node.js has an HTTP and an HTTPS module. HTTPS makes the requests through the Transport Layer Security (TLS/SSL). However, if we are making requests to and from URLs that only have HTTP, then we would use the HTTP module.

Now use the HTTP object to make a GET request to the API to retrieve a list of users. We will use JSON Placeholder, a publicly available API for testing. It simulates a real server, and returns mocked responses as long as we send a valid request.

In a text editor, run:

const https = require(‘https’);

let request = https.get(‘https://jsonplaceholder.typicode.com/users?_limit=2’, (res) => { });

HTTP responses come with a status code. A status code is a number that indicates how successful the response was. Status codes between 200 and 299 are positive responses, while codes between 400 and 599 are errors.

Add the following code to the callback function:

const https = require(‘https’);

let request = https.get(‘https://jsonplaceholder.typicode.com/users?_limit=2’, (res) => {
if (res.statusCode !== 200) {
console.error(`Did not get an OK from the server. Code: ${res.statusCode}`);
res.resume();
return;
}
});

The response object has a statusCode property that stores the status code. If it is not 200, we log an error to the console and exit.

Now we add code to read the data. The strategy for retrieving data will be to listen for when data comes from the response, collate all the chunks, and then parse the JSON so the application can use it.

Modify the request callback to include this code:

const https = require(‘https’);

let request = https.get(‘https://jsonplaceholder.typicode.com/users?_limit=2’, (res) => {
if (res.statusCode !== 200) {
console.error(`Did not get an OK from the server. Code: ${res.statusCode}`);
res.resume();
return;
}

let data = ”;

res.on(‘data’, (chunk) => {
data += chunk;
});

res.on(‘close’, () => {
console.log(‘Retrieved all data’);
console.log(JSON.parse(data));
});
});

We begin by creating a new variable data. We can store data as an array of numbers representing byte data or a string.

After creating the data variable, we create an event listener. When the response object emits a data event, we will take the data it received and add it to the data variable.

Once we receive all the data, Node.js emits a close event. At this point, we parse the JSON string stored in data and log the result to the console.

The Node.js module can now communicate with the JSON API and log the list of users.

This script will throw an error if we are unable to make a request. Add the following code to capture errors when you are unable to send an HTTP request:

…
res.on(‘data’, (chunk) => {
data += chunk;
});

res.on(‘close’, () => {
console.log(‘Retrieved all data’);
console.log(JSON.parse(data));
});

});

request.on(‘error’, (err) => {
console.error(`Encountered an error trying to make a request: ${err.message}`);
});

When a request fails to send, the request object emits an error event. If it is emitted but not listened to, the Node.js program crashes.

Therefore, to capture errors we add an event listener with the on() function and listen for error events.

Save and exit nano by pressing CTRL+X.

Now we execute this program with node:

$ node getRequestWithGet.js

Our console output will be similar to this:

Retrieved all data
[
{
id: 1,
name: ‘Leanne Graham’,
username: ‘Bret’,
email: ‘Sincere@april.biz’,
address: {
street: ‘Kulas Light’,
suite: ‘Apt. 556’,
city: ‘Gwenborough’,
zipcode: ‘92998-3874’,
geo: [Object]
},
phone: ‘1-770-736-8031 x56442’,
website: ‘hildegard.org’,
company: {
name: ‘Romaguera-Crona’,
catchPhrase: ‘Multi-layered client-server neural-net’,
bs: ‘harness real-time e-markets’
}
},
{
id: 2,
name: ‘Ervin Howell’,
username: ‘Antonette’,
email: ‘Shanna@melissa.tv’,
address: {
street: ‘Victor Plains’,
suite: ‘Suite 879’,
city: ‘Wisokyburgh’,
zipcode: ‘90566-7771’,
geo: [Object]
},
phone: ‘010-692-6593 x09125’,
website: ‘anastasia.net’,
company: {
name: ‘Deckow-Crist’,
catchPhrase: ‘Proactive didactic contingency’,
bs: ‘synergize scalable supply-chains’
}
}
]
  • Making Requests with request()

The request() method supports multiple function signatures. For example,

https.request(URL_String, Options_Object, Callback_Function) {
Action
}.

Eventually, create a new file for a new module, getRequestWithRequest.js:

$ nano getRequestWithRequest.js

The code we write is similar to the earlier getRequestWithGet.js module. Initially, import the https module:

const https = require(‘https’);

Then, we create a new JavaScript object that contains a method key:

const https = require(‘https’);

const options = {
method: ‘GET’
};

Next, make the request in the code. In an editor, enter the following lines:

…

let request = https.request(‘https://jsonplaceholder.typicode.com/users?_limit=2’, options, (res) => {
if (res.statusCode !== 200) {
console.error(`Did not get an OK from the server. Code: ${res.statusCode}`);
res.resume();
return;
}

let data = ”;

res.on(‘data’, (chunk) => {
data += chunk;
});

res.on(‘close’, () => {
console.log(‘Retrieved all data’);
console.log(JSON.parse(data));
});
});

request.end();

request.on(‘error’, (err) => {
console.error(`Encountered an error trying to make a request: ${err.message}`);
});

To make a request using request(), we provide the URL in the first argument, an object with the HTTP options in the second argument, and a callback to handle the response in the third argument.

We call the end() method of the request variable. It completes the request, allowing it to be sent. If we do not call it, the program will never complete.

Save and exit nano with CTRL+X, or the equivalent with the text editor.

Then we run:

$ node getRequestWithRequest.js

Our output will be similar to the first module:

Retrieved all data
[
{
id: 1,
name: ‘Leanne Graham’,
username: ‘Bret’,
email: ‘Sincere@april.biz’,
address: {
street: ‘Kulas Light’,
suite: ‘Apt. 556’,
city: ‘Gwenborough’,
zipcode: ‘92998-3874’,
geo: [Object]
},
phone: ‘1-770-736-8031 x56442’,
website: ‘hildegard.org’,
company: {
name: ‘Romaguera-Crona’,
catchPhrase: ‘Multi-layered client-server neural-net’,
bs: ‘harness real-time e-markets’
}
},
{
id: 2,
name: ‘Ervin Howell’,
username: ‘Antonette’,
email: ‘Shanna@melissa.tv’,
address: {
street: ‘Victor Plains’,
suite: ‘Suite 879’,
city: ‘Wisokyburgh’,
zipcode: ‘90566-7771’,
geo: [Object]
},
phone: ‘010-692-6593 x09125’,
website: ‘anastasia.net’,
company: {
name: ‘Deckow-Crist’,
catchPhrase: ‘Proactive didactic contingency’,
bs: ‘synergize scalable supply-chains’
}
}
]

It is important to know this function as it allows to customize the request in ways the get() method cannot.

 

Step 2 – Configure HTTP request() Options

The request() function allows us to send HTTP requests without specifying the URL in the first argument.

https.request(Options_Object, Callback_Function) {
Action
}

Here, we will use this functionality to configure the request() with the options object.

Node.js allows us to enter the URL in the options object we pass to the request:

$ nano getRequestWithRequest.js

Make sure to remove the URL from the request() call so that the only arguments are the options variable and the callback function:

const https = require(‘https’);

const options = {
method: ‘GET’,
};

let request = https.request(options, (res) => {
…

Now we add the following properties to the options object:

const https = require(‘https’);

const options = {
host: ‘jsonplaceholder.typicode.com’,
path: ‘/users?_limit=2’,
method: ‘GET’
};

let request = https.request(options, (res) => {
…

The Accept header specifies the type of data the user can handle. While the API these examples only return JSON, we can add the Accept header to explicitly state that we want JSON.

We add the following lines of code to append the Accept header:

const https = require(‘https’);

const options = {
host: ‘jsonplaceholder.typicode.com’,
path: ‘/users?_limit=2’,
method: ‘GET’,
headers: {
‘Accept’: ‘application/json’
}
};

By adding headers, we cover the four most popular options that are sent in Node.js HTTP requests: host, path, method, and headers.

Eventually, enter CTRL+X to save the file and exit nano.

Next, we run code once more to make the request by only using options:

$ node getRequestWithRequest.js

We will receive an output similar to this:

Retrieved all data
[
{
id: 1,
name: ‘Leanne Graham’,
username: ‘Bret’,
email: ‘Sincere@april.biz’,
address: {
street: ‘Kulas Light’,
suite: ‘Apt. 556’,
city: ‘Gwenborough’,
zipcode: ‘92998-3874’,
geo: [Object]
},
phone: ‘1-770-736-8031 x56442’,
website: ‘hildegard.org’,
company: {
name: ‘Romaguera-Crona’,
catchPhrase: ‘Multi-layered client-server neural-net’,
bs: ‘harness real-time e-markets’
}
},
{
id: 2,
name: ‘Ervin Howell’,
username: ‘Antonette’,
email: ‘Shanna@melissa.tv’,
address: {
street: ‘Victor Plains’,
suite: ‘Suite 879’,
city: ‘Wisokyburgh’,
zipcode: ‘90566-7771’,
geo: [Object]
},
phone: ‘010-692-6593 x09125’,
website: ‘anastasia.net’,
company: {
name: ‘Deckow-Crist’,
catchPhrase: ‘Proactive didactic contingency’,
bs: ‘synergize scalable supply-chains’
}
}
]

 

Step 3 – Make a POST Request

When we upload data to a server or want the server to create data, we typically send a POST request.

Despite being a different method from GET, we will reuse code from the previous requests when writing the POST request. However, we will have to make the following adjustments:

  • Change the method in the options object to POST
  • Add a header to state you are uploading JSON
  • Check the status code to confirm a user was created
  • Upload the new user’s data

To make these changes, first, we create a new file called postRequest.js. Open this file in a text editor:

$ nano postRequest.js

We begin by importing the HTTPS module and creating an options object:

const https = require(‘https’);

const options = {
host: ‘jsonplaceholder.typicode.com’,
path: ‘/users’,
method: ‘POST’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json; charset=UTF-8’
}
};

Next, make the request with the request() function. We add the following lines to the end the code:

…
const request = https.request(options, (res) => {
if (res.statusCode !== 201) {
console.error(`Did not get a Created from the server. Code: ${res.statusCode}`);
res.resume();
return;
}

let data = ”;

res.on(‘data’, (chunk) => {
data += chunk;
});

res.on(‘close’, () => {
console.log(‘Added new user’);
console.log(JSON.parse(data));
});
});

The code checks if the status code is 201. The 201 status code indicates that the server created a resource.

This POST request is to create a new user. For this API, we need to upload the user details:

…

const requestData = {
name: ‘New User’,
username: ‘digitalocean’,
email: ‘user@digitalocean.com’,
address: {
street: ‘North Pole’,
city: ‘Murmansk’,
zipcode: ‘12345-6789’,
},
phone: ‘555-1212’,
website: ‘digitalocean.com’,
company: {
name: ‘DigitalOcean’,
catchPhrase: ‘Welcome to the developer cloud’,
bs: ‘cloud scale security’
}
};

request.write(JSON.stringify(requestData));

First, we create the requestData variable, which is a JavaScript object containing user data. The request does not include an id field, as servers typically generate these while saving the new data.

We next use the request.write() function, which accepts a string or buffer object to send along with the request. As the requestData variable is an object, we use the JSON.stringify function to convert it to a string.

To complete, end the request and check for errors:
…

request.end();

request.on(‘error’, (err) => {
console.error(`Encountered an error trying to make a request: ${err.message}`);
});

Make sure to write data before we use the end() function. The end() function tells Node.js that there is no more data to add to the request and sends it.

Save and exit nano by pressing CTRL+X.

To confirm the new user, we run this program:

$ node postRequest.js

The output will confirm that the request was successful:

Added new user
{
name: ‘New User’,
username: ‘digitalocean’,
email: ‘user@digitalocean.com’,
address: { street: ‘North Pole’, city: ‘Murmansk’, zipcode: ‘12345-6789’ },
phone: ‘555-1212’,
website: ‘digitalocean.com’,
company: {
name: ‘DigitalOcean’,
catchPhrase: ‘Welcome to the developer cloud’,
bs: ‘cloud scale security’
},
id: 11
}

The API returns the user data that was uploaded, along with the ID that was assigned to it.

 

Step 4 – Make a PUT Request

Developers make a PUT request to upload data to a server.

In practice, the code we write is similar to that of a POST request. We set up options, make requests, write the data to upload and verify the response.

Since the code is similar to the POST request, we will use that module as a base for this one. Copy the postRequest.js into a new file, putRequest.js:

$ cp postRequest.js putRequest.js

In a text editor, open putRequest.js:

$ nano putRequest.js

Make these changes to send a PUT request to https://jsonplaceholder.typicode.com/users/1:

const https = require(‘https’);

const options = {
host: ‘jsonplaceholder.typicode.com’,
path: ‘/users/1’,
method: ‘PUT’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json; charset=UTF-8’
}
};

const request = https.request(options, (res) => {
if (res.statusCode !== 200) {
console.error(`Did not get an OK from the server. Code: ${res.statusCode}`);
res.resume();
return;
}

let data = ”;

res.on(‘data’, (chunk) => {
data += chunk;
});

res.on(‘close’, () => {
console.log(‘Updated data’);
console.log(JSON.parse(data));
});
});

const requestData = {
username: ‘digitalocean’
};

request.write(JSON.stringify(requestData));

request.end();

request.on(‘error’, (err) => {
console.error(`Encountered an error trying to make a request: ${err.message}`);
});

Eventually, save and exit nano with CTRL+X.

Then we execute the Node.js program in the terminal:

$ node putRequest.js

We will receive an output like this:

Updated data
{ username: ‘digitalocean’, id: 1 }

We sent a PUT request to update a pre-existing user.

 

Step 5 – Make a DELETE Request

The DELETE request is to remove data from a server. In this section, we will delete a user using the API.

The code we write is similar to that of a GET request, so we use it as a base here. Copy the getRequestWithRequest.js file into a new deleteRequest.js file:

$ cp getRequestWithRequest.js deleteRequest.js

We open deleteRequest.js with nano:

$ nano deleteRequest.js

Then we modify the code to delete the first user in the API:

const https = require(‘https’);

const options = {
host: ‘jsonplaceholder.typicode.com’,
path: ‘/users/1’,
method: ‘DELETE’,
headers: {
‘Accept’: ‘application/json’,
}
};

const request = https.request(options, (res) => {
if (res.statusCode !== 200) {
console.error(`Did not get an OK from the server. Code: ${res.statusCode}`);
res.resume();
return;
}

let data = ”;

res.on(‘data’, (chunk) => {
data += chunk;
});

res.on(‘close’, () => {
console.log(‘Deleted user’);
console.log(JSON.parse(data));
});
});

request.end();

request.on(‘error’, (err) => {
console.error(`Encountered an error trying to make a request: ${err.message}`);
});

Eventually, save and exit this file by pressing CTRL+X.

To confirm it works, we run:

$ node deleteRequest.js

The output will be like this:

Deleted user
{}

While the API does not return a response body, we still got a 200 response so the request was OK.

[Stuck with the procedures? We can help you]

 

Conclusion

In short, we made GET, POST, PUT, and DELETE requests in Node.js. Today, we saw how our Support Techs create HTTP Client in Node.js

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = "owonCMyG5nEQ0aD71QM";

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Never again lose customers to poor
server speed! Let us help you.