Dhanu Gurung
Dhanu Gurung

Reputation: 8840

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

What is actual difference between res.send and res.json as both seems to perform same operation of responding to client.

Upvotes: 287

Views: 166673

Answers (4)

Steven Spungin
Steven Spungin

Reputation: 29091

res.json forces the argument to JSON. res.send will take an non-json object or non-json array and send another type. For example:

This will return a JSON number.

res.json(100)

This will return a status code and issue a warning to use sendStatus.

res.send(100)

If your argument is not a JSON object or array (null, undefined, boolean, string), and you want to ensure it is sent as JSON, use res.json.

Upvotes: 3

hexacyanide
hexacyanide

Reputation: 91639

The methods are identical when an object or array is passed, but res.json() will also convert non-objects, such as null and undefined, which are not valid JSON.

The method also uses the json replacer and json spaces application settings, so you can format JSON with more options. Those options are set like so:

app.set('json spaces', 2);
app.set('json replacer', replacer);

And passed to a JSON.stringify() like so:

JSON.stringify(value, replacer, spacing);
// value: object to format
// replacer: rules for transforming properties encountered during stringifying
// spacing: the number of spaces for indentation

This is the code in the res.json() method that the res.send() method doesn't have:

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

The method ends up as a res.send() in the end:

this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');

return this.send(body);

Upvotes: 276

Roger Heathcote
Roger Heathcote

Reputation: 3525

Looking in the headers sent...

res.send uses content-type:text/html

res.json uses content-type:application/json

edit: send actually changes what is sent based on what it's given, so strings are sent as text/html, but if you pass it an object it emits application/json.

Upvotes: 29

Peter Lyons
Peter Lyons

Reputation: 146014

See: res.json source code on expressjs.

res.json eventually calls res.send, but before that it:

  • respects the json spaces and json replacer app settings
  • ensures the response will have utf-8 charset and application/json Content-Type

Upvotes: 99

Related Questions