English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer&URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

NodeJS Other

Node.js request Module

GET requests

GET requests are those that request a site to provide specific resources or certain data.

In this Node.js tutorial, we will learn how to use the request module to handle GET requests from HTTP web servers in Node.js to other websites.

Using the request Node.js module to handle GET requests

Node.js has a module named "request" that can help us make requests to another website. We will start from the installationStarting with the Node.js request module.

Install the "request" Node.js module

Open the terminal or command prompt and run the following command to install the request Node.js module

$npm install request

Example of Node.js GET request

The following is an example Node.js file that will include the request module. It requests to get the resource " http://www.google.com. The callback function provided as the second parameter receives error (if any), response, and body.

// Using the Node.js request module to handle GET requests
// Introducing the request module
var request = require("request"); 
 
//Resource "http://www.google.com" send a get request 
request("http://www.google.com",function(error,response,body) 
 { 
    console.log(response); 
 });

Run the above Node.js file in the terminal as follows

$node serverGetRequests.js

The response will be echoed to the console.

If there are no errors with the GET request, the contentErrorIsZeroThis information can be used to check for any errors in the 'GET requests' for resources.

Example of Node.js Get Request Error

In some cases, we may encounter errors when making 'GET requests' for resources. The following example is one of these cases, where the provided URL is incorrect.

 
// Include the 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 learned how to use the request module to handle 'GET requests' to other websites from the HTTP web server in Node.js.