a blog for those who code

Thursday 28 January 2016

How to Intercept HTTP requests in Node.js

In this post we will be discussing about intercepting HTTP requests in Node.js. We will be using Nock, a node module which intercepts requests and allows you to respond to them as you wish. It can be used to test modules that perform HTTP requests in isolation. Intercepting HTTP requests are very useful for doing unit testing of your application if you are calling any third party APIs.

Installation

npm install nock

Usage

Example 1 : Access homepage of Google

In this example we are intercepting a GET request to a given host (http://www.google.com) + path ('/') and responding  with a desired response code and contents.

var nock = require('nock');

var response = nock('http://www.google.com')
.get('/')
.reply(200, 'Hello Google');

console.log(response);

The Above code will give us an output as below


Example 2 : Access an API

In this example we are intercepting a GET request to a given host (http://jsonplaceholder.typicode.com) + path ('/comments?postId=1') and responding with a desired response code and contents.

var nock = require('nock');

var response = nock('http://jsonplaceholder.typicode.com')
.get('/comments?postId=1')
.reply(200, 'Hello JsonPlaceHolder');

console.log(response);

The Above code will give us an output as below


In short nock intercepts the requests and throws back what you want. This post is a very basic post of nock. If you need any more information feel free to contact us. Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment