Handle Get Requests using request Node.js module

Get Requests

Get requests are those which request a site for a specified resource or some data.

In this Node.js Tutorial, we shall learn how to handle Get Requests to other websites from our HTTP Web Server in Node.js using request module.

To learn about creating HTTP Web Server, please refer Create a HTTP Web Server in Node.js.

Handle Get Requests using request Node.js module

There is module called ‘request’ for Node.js, which could help us to make get requests to another website. We shall start with installing the request Node.js module.

Install ‘request’ Node.js Module

Open a Terminal or Command prompt and run the following command to install request Node.js module

$ npm install request

Example Node.js file with Get Request

Following is an example Node.js file in which we shall include request module. And make a get request for the resource “http://www.google.com”. Call back function provided as second argument receives error(if any), response and body.

Run the above Node.js file in the terminal as shown in the following

$ node serverGetRequests.js

The response would be echoed back to the console.

If there is no error with the get request, the content of error would be null. This information could be used as a check if there is any error in the get request made for a resource.

Example Node.js file with Get Request receiving error

There could be scenarios during which we might get an error for Get Request we do for a resource. Following example is a scenario of such where the url provided is bad.

 

Conclusion :

In this Node.js Tutorial, we have learnt how to handle Get Requests to other websites from our HTTP Web Server in Node.js using request module.