A growing trend has been to use JSON data to transfer information from a server to a client and then have the client dynamically populate the HTML elements on the page rather than have the server build HTML documents or parts of HTML documents and send the HTML to the client. Express facilitates sending JSON very nicely by providing the json()
and jsonp()
methods on the Response
object. These methods use a syntax similar to that of send()
, except that the body is a JSON stringify JavaScript object:
res.json(status, [object])
res.json([body])
res.jsonp(status, [object])
res.jsonp([object])
The JavaScript object is converted to a JSON string and sent back to the client. In the case of jsonp()
, the URL of the request object includes a ?callback=<method>
parameter, and the JSON string is wrapped in a function with the method name that can be called from the browser client to support the JSONP design.
Listing 18.5 implements both json()
and jsonp()
to illustrate sending JSON data to the server. Notice that in line 6 the json spaces
application setting is set to 4
, and a basic JavaScript object is passed into the json()
call on line 7. On line 12 an error code is set in the response, and the response object is a JSON object.
Lines 14–19 implement the jsonp()
method. Notice that jsonp callback name
is set to cb
in line 15. This means that instead of passing ?callback=<function>
in the URL, the client needs to pass ?cb=<function>
in the URL. Figure 18.4 shows the output to the browser for each of these calls.
01 var express = require('express'),
02 var url = require('url'),
03 var app = express();
04 app.listen(80);
05 app.get('/json', function (req, res) {
06 app.set('json spaces', 4);
07 res.json({name:"Smithsonian", built:'1846', items:'137M',
08 centers: ['art', 'astrophysics', 'natural history',
09 'planetary', 'biology', 'space', 'zoo']});
10 });
11 app.get('/error', function (req, res) {
12 res.json(500, {status:false, message:"Internal Server Error"});
13 });
14 app.get('/jsonp', function (req, res) {
15 app.set('jsonp callback name', 'cb'),
16 res.jsonp({name:"Smithsonian", built:'1846', items:'137M',
17 centers: ['art', 'astrophysics', 'natural history',
18 'planetary', 'biology', 'space', 'zoo']});
19 });