Node.js – 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 1 – 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.

serverGetRequests.js

</>
Copy
// Example to Handle Get Requests using request Node.js module
// include request module
var request = require("request");

// make a get request for the resource "http://www.google.com"
request("http://www.google.com",function(error,response,body)
{
	console.log(response);
});

Open a terminal and run the following command to execute this Node.js file.

$ 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 2 – 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.

serverGetRequestsError.js

</>
Copy
// include request module
var request = require("request");

// make a get request for the resource "http://www.go1411ogle.com"
request("http://www.go1411ogle.com",function(error,response,body)
{
	console.log(error);
});

Terminal Output

$ node serverGetRequestsError.js 
{ Error: getaddrinfo ENOTFOUND www.go1411ogle.com www.go1411ogle.com:80
    at errnoException (dns.js:53:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:95:26)
  code: 'ENOTFOUND',
  errno: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'www.go1411ogle.com',
  host: 'www.go1411ogle.com',
  port: 80 }

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.