a blog for those who code

Friday 10 June 2016

Difference between res.send and res.json in Express.js

In this post we will be discussing about difference between res.send and res.json in Express.js. The res (or response) object represents the HTTP response that an Express application sends when it gets an HTTP request. Mostly you encounter response and request object in a Restful applications where you need HTTP requests to post data, get data or delete data.

What is res.send and res.json

res.send([body | status], [body]) : It sends a response and performs useful tasks for simple non-streaming responses like automatically assigning Content-Length and providing automatic HEAD and HTTP cache freshness support.

res.json([status | body], [body]) : It sends a JSON response. This method is identical to res.send() when an object or array is passed, but it also converts non-objects to json.

Difference Between res.send and res.json 

There is no actual difference between res.send and res.json, both methods are almost identical. res.json calls res.send at the end. When you have an object or array which you have to pass as a response then you can use any one of them. 

But the main difference between res.json and res.send comes into picture when you have to pass non objects as a response. res.json will convert non objects (ex. null, undefined etc) as well which are actually not a valid JSON whereas res.send will not convert them.

res.json also uses json replacer and json spaces application settings.

json replacer : It is a setting which is passed to JSON.stringify() for allowing you to manipulate and filter the JSON response.

json spaces : Its is a setting which enables the developer to decide if res.json() responds with nicely formatte JSON or compact JSON.

The below code is the add on in res.json over res.send.

var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.strigify(obj, replacer, spaces);

return this.send(body);

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment