Making GET Requests in Node.JS

nodejs
Published on May 16, 2019

This tutorial we shall discuss initiating HTTP GET request through Node. This can be used to implement third party API calls.

Modules Required

  • The http module is required to make HTTP requests through Node. This module is built-in to Node.

    const http = require('http');
  • However if you're making HTTPS requests you will need the https module. Both modules are the same, they have the same function names — just the module names differ. This tutorial will use the http module, however the same code holds for the https module also.

    const https = require('https');
  • While sending GET requests to a sever, the data is sent to the url as a query string, for example http://usefulangle.com/example.php?id=123&type=post. This query string can be created using the querystring module.

    const querystring = require('querystring');

    This module is also built-in to Node.

Sending GET Request

The GET request is sent by calling the request method of the http module. Various options for the GET request can be set through a parameter.

const http = require('http');
const querystring = require('querystring');

// GET parameters
const parameters = {
	id: 123,
	type: "post"
}

// GET parameters as query string : "?id=123&type=post"
const get_request_args = querystring.stringify(parameters);

// Final url is "http://usefulangle.com/get/ajax.php?id=123&type=post"
const options = {
	url: "http://www.usefulangle.com",
	port: "80",
	path: "/get/ajax.php?" + get_request_args,
	headers : {
		'Content-Type': 'application/x-www-form-urlencoded'
	}
}

// send request
const request = http.request(options, (response) => {
	// response from server
});

// In case error occurs while sending request
request.on('error', (error) => {
	console.log(error.message);
});

request.end();

Errors may occur while sending the request. This is handled by listening to the error event on the request object.

Getting Response from Server

A callback is passed to the http.request method while handles the response received from the server.

const request = http.request(options, (response) => {
	// response from server

	// HTTP status code (200, 404 etc)
	console.log(response.statusCode);

	// response headers
	console.log(response.headers);
});

The response data from the server comes in chunks. The response might be a single chunk for small response or a series on chunks for larger responses. To get the body of the response, these chunks are collected and merged through events.

The data event is emitted when a chunk arrives and the end event is emitted when all chunks have arrived.

const request = http.request(options, (response) => {
	// array to hold all chunks
	let all_chunks = [];

	// gather chunks
	response.on('data', (chunk) => {
		all_chunks.push(chunk);
	});

	// no more data to come
	// combine all chunks to a buffer
	response.on('end', () => {
		let response_body = Buffer.concat(all_chunks);
		
		// response body as string
		console.log(response_body.toString());

		// read the response body now
	});

	// handle error while getting response
	response.on('error', (error) => {
		console.log(error.message);
	});
});

Complete Code

const http = require('http');
const querystring = require('querystring');

const parameters = {
	id: 123,
	type: "post"
}
const get_request_args = querystring.stringify(parameters);

const options = {
	url: "http://www.usefulangle.com",
	port: "80",
	path: "/get/ajax.php?" + get_request_args,
	headers : {
		'Content-Type': 'application/x-www-form-urlencoded'
	}
}

const request = http.request(options, (response) => {
	let all_chunks = [];

	response.on('data', (chunk) => {
		all_chunks.push(chunk);
	});

	response.on('end', () => {
		let response_body = Buffer.concat(all_chunks);
		console.log(response_body.toString());
	});

	response.on('error', (error) => {
		console.log(error.message);
	});
});

request.on('error', (error) => {
	console.log(error.message);
});

request.end();

Useful Resources

In this Tutorial