Skip to content
Myr

Added res.json() and tests

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent e4342a7 · Browse files · 2 files+63 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+63 added−0 removed

  • tests:+39 added−0 removed
  • other:+24 added−0 removed

2 files+63 added−0 removed

modified:lib/response.js+24 added
112 unmodified lines
113114 // respond115 this.statusCode = status;116 this.end('HEAD' == this.req.method ? undefined : body);117 return this;118};119120/**121 * Send JSON response with `obj`, optional `headers`, and optional `status`.122 *123 * Examples:124 *125 * res.json(null);126 * res.json({ user: 'tj' });127 * res.json('oh noes!', 500);128 * res.json('I dont have that', 404);129 *130 * @param {Mixed} obj131 * @param {Object|Number} headers or status132 * @param {Number} status133 * @return {ServerResponse}134 * @api public135 */136137res.json = function(obj, headers, status){138 this.charset = this.charset || 'utf-8';139 this.header('Content-Type', 'application/json');140 return this.send(JSON.stringify(obj), headers, status);141};142143/**144 * Transfer the file at the given `path`. Automatically sets 145 * the _Content-Type_ response header field. `next()` is called146 * when `path` is a directory, or when an error occurs.147 *
299 unmodified lines
modified:test/response.test.js+39 added
7 unmodified lines
8 , assert = require('assert')9 , should = require('should');1011module.exports = {12 'test #json()': function(){13 var app = express.createServer()14 , json = 'application/json; charset=utf-8';1516 app.get('/user', function(req, res, next){17 res.json({ name: 'tj' });18 });1920 app.get('/string', function(req, res, next){21 res.json('whoop!');22 });2324 app.get('/error', function(req, res, next){25 res.json('oh noes!', 500);26 });2728 app.get('/headers', function(req, res, next){29 res.json(undefined, { 'X-Foo': 'bar' }, 302);30 });3132 assert.response(app,33 { url: '/error' },34 { body: '"oh noes!"'35 , status: 50036 , headers: { 'Content-Type': json }});3738 assert.response(app,39 { url: '/string' },40 { body: '"whoop!"'41 , headers: {42 'Content-Type': json43 , 'Content-Length': 844 }});4546 assert.response(app,47 { url: '/user' },48 { body: '{"name":"tj"}', headers: { 'Content-Type': json }});49 },5051 'test #send()': function(){52 var app = express.createServer();53 54 app.get('/html', function(req, res){
606 unmodified lines