response.js
This file
Path
lib/response.js
647 lines · 15.0 KiB · JavaScript
Last changed by
Fixed: expose connects mime module. Cloases #1165TJ Holowaychukbefore adoption8956731
History of this fileTake it
The walk stopped after 200 commits: lines older than d115798 point at it.
ocdTJ Holowaychukbefore adoptiond115798
lines 1–10why, one step back12/**3 * Module dependencies.4 */56var fs = require('fs')7 , http = require('http')8 , path = require('path')9 , connect = require('connect')10 , utils = connect.utilsAdded array support. Closes #1053TJ Holowaychukbefore adoption298899d
lines 11–12why, one step back11 , normalizeType = require('./utils').normalizeType12 , normalizeTypes = require('./utils').normalizeTypesocdTJ Holowaychukbefore adoptiond115798
lines 13–14why, one step back13 , statusCodes = http.STATUS_CODES14 , send = connect.static.sendfixing cookies for connect 2.3.1TJ Holowaychukbefore adoption02d4384
line 15why, one step back15 , cookie = require('cookie')Added Buffer ETag support to res.send()TJ Holowaychukbefore adoptionc0a68fc
line 16why, one step back16 , crc = require('crc')Fixed: expose connects mime module. Cloases #1165TJ Holowaychukbefore adoption8956731
line 17why, one step back17 , mime = connect.mimeocdTJ Holowaychukbefore adoptiond115798
line 18why, one step back18 , basename = path.basenameChanged to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95
line 19why, one step back19 , extname = path.extnameocdTJ Holowaychukbefore adoptiond115798
lines 20–61why, one step back20 , join = path.join;2122/**23 * Response prototype.24 */2526var res = module.exports = {27 __proto__: http.ServerResponse.prototype28};2930/**31 * Set status `code`.32 *33 * @param {Number} code34 * @return {ServerResponse}35 * @api public36 */3738res.status = function(code){39 this.statusCode = code;40 return this;41};4243/**44 * Send a response.45 *46 * Examples:47 *48 * res.send(new Buffer('wahoo'));49 * res.send({ some: 'json' });50 * res.send('<p>some html</p>');51 * res.send(404, 'Sorry, cant find that');52 * res.send(404);53 *54 * @param {Mixed} body or status55 * @param {Mixed} body56 * @return {ServerResponse}57 * @api public58 */5960res.send = function(body){61 var req = this.reqAdded conditional-GET support to res.send()TJ Holowaychukbefore adoptiona58e3de
lines 62–63why, one step back62 , head = 'HEAD' == req.method63 , len;ocdTJ Holowaychukbefore adoptiond115798
lines 64–69why, one step back6465 // allow status / body66 if (2 == arguments.length) {67 this.statusCode = body;68 body = arguments[1];69 }Merge pull request #1100 from coolony/masterTJ Holowaychukbefore adoption1ddf0c8
line 70why, one step back70 refactored res.send()TJ Holowaychukbefore adoptionb809041
lines 71–72why, one step back71 // convert string objects to primitives72 if (body instanceof String) body = body.toString();ocdTJ Holowaychukbefore adoptiond115798
lines 73–76why, one step back7374 switch (typeof body) {75 // response status76 case 'number':.contentType -> .type() in coreTJ Holowaychukbefore adoption7c2e1ad
line 77why, one step back77 this.get('Content-Type') || this.type('txt');ocdTJ Holowaychukbefore adoptiond115798
lines 78–84why, one step back78 this.statusCode = body;79 body = http.STATUS_CODES[body];80 break;81 // string defaulting to html82 case 'string':83 if (!this.get('Content-Type')) {84 this.charset = this.charset || 'utf-8';.contentType -> .type() in coreTJ Holowaychukbefore adoption7c2e1ad
line 85why, one step back85 this.type('html');ocdTJ Holowaychukbefore adoptiond115798
lines 86–92why, one step back86 }87 break;88 case 'boolean':89 case 'object':90 if (null == body) {91 body = '';92 } else if (Buffer.isBuffer(body)) {.contentType -> .type() in coreTJ Holowaychukbefore adoption7c2e1ad
line 93why, one step back93 this.get('Content-Type') || this.type('bin');ocdTJ Holowaychukbefore adoptiond115798
lines 94–101why, one step back94 } else {95 return this.json(body);96 }97 break;98 }99100 // populate Content-Length101 if (undefined !== body && !this.get('Content-Length')) {Added Buffer ETag support to res.send()TJ Holowaychukbefore adoptionc0a68fc
lines 102–104why, one step back102 this.set('Content-Length', len = Buffer.isBuffer(body)103 ? body.length104 : Buffer.byteLength(body));Added conditional-GET support to res.send()TJ Holowaychukbefore adoptiona58e3de
lines 105–108why, one step back105 }106107 // ETag support108 // TODO: W/ supportAdded Buffer ETag support to res.send()TJ Holowaychukbefore adoptionc0a68fc
line 109why, one step back109 if (len > 1024) {Changed: res.send() only set ETag when not previously setTJ Holowaychukbefore adoption1a3e40d
line 110why, one step back110 if (!this.get('ETag')) this.set('ETag', Buffer.isBuffer(body)Added Buffer ETag support to res.send()TJ Holowaychukbefore adoptionc0a68fc
lines 111–112why, one step back111 ? crc.buffer.crc32(body)112 : crc.crc32(body));Added conditional-GET support to res.send()TJ Holowaychukbefore adoptiona58e3de
line 113why, one step back113 if (req.fresh) this.statusCode = 304;ocdTJ Holowaychukbefore adoptiond115798
lines 114–150why, one step back114 }115116 // strip irrelevant headers117 if (204 == this.statusCode || 304 == this.statusCode) {118 this.removeHeader('Content-Type');119 this.removeHeader('Content-Length');120 body = '';121 }122123 // respond124 this.end(head ? null : body);125 return this;126};127128/**129 * Send JSON response.130 *131 * Examples:132 *133 * res.json(null);134 * res.json({ user: 'tj' });135 * res.json(500, 'oh noes!');136 * res.json(404, 'I dont have that');137 *138 * @param {Mixed} obj or status139 * @param {Mixed} obj140 * @return {ServerResponse}141 * @api public142 */143144res.json = function(obj){145 // allow status / body146 if (2 == arguments.length) {147 this.statusCode = obj;148 obj = arguments[1];149 }150Fixed: use app.get() for all core settingsTJ Holowaychukbefore adoption8f87400
lines 151–154why, one step back151 var app = this.app152 , jsonp = app.get('jsonp callback')153 , replacer = app.get('json replacer')154 , spaces = app.get('json spaces')ocdTJ Holowaychukbefore adoptiond115798
lines 155–162why, one step back155 , body = JSON.stringify(obj, replacer, spaces)156 , callback = this.req.query.callback;157158 this.charset = this.charset || 'utf-8';159 this.set('Content-Type', 'application/json');160161 if (callback && jsonp) {162 this.set('Content-Type', 'text/javascript');Added: allow [] in jsonp callback. Closes #1128TJ Holowaychukbefore adoptiondf2584c
line 163why, one step back163 body = callback.replace(/[^[]\w$.]/g, '') + '(' + body + ');';ocdTJ Holowaychukbefore adoptiond115798
lines 164–182why, one step back164 }165166 return this.send(body);167};168169/**170 * Transfer the file at the given `path`.171 * 172 * Automatically sets the _Content-Type_ response header field.173 * The callback `fn(err)` is invoked when the transfer is complete174 * or when an error occurs. Be sure to check `res.sentHeader`175 * if you wish to attempt responding, as the header and some data176 * may have already been transferred.177 *178 * Options:179 *180 * - `maxAge` defaulting to 0181 * - `root` root directory for relative filenames182 *Added new dox API docsTJ Holowaychukbefore adoption7e81cad
lines 183–202why, one step back183 * Examples:184 *185 * The following example illustrates how `res.sendfile()` may186 * be used as an alternative for the `static()` middleware for187 * dynamic situations. The code backing `res.sendfile()` is actually188 * the same code, so HTTP cache support etc is identical.189 *190 * app.get('/user/:uid/photos/:file', function(req, res){191 * var uid = req.params.uid192 * , file = req.params.file;193 * 194 * req.user.mayViewFilesFrom(uid, function(yes){195 * if (yes) {196 * res.sendfile('/uploads/' + uid + '/' + file);197 * } else {198 * res.send(403, 'Sorry! you cant see that.');199 * }200 * });201 * });202 *ocdTJ Holowaychukbefore adoptiond115798
lines 203–224why, one step back203 * @param {String} path204 * @param {Object|Function} options or fn205 * @param {Function} fn206 * @api public207 */208209res.sendfile = function(path, options, fn){210 var self = this211 , req = self.req212 , next = this.req.next213 , options = options || {};214215 // support function as second arg216 if ('function' == typeof options) {217 fn = options;218 options = {};219 }220221 // callback222 options.callback = function(err){223 if (err) {224 // cast ENOENTrefactored res.sendfile()TJ Holowaychukbefore adoptioncf7d710
line 225why, one step back225 if ('ENOENT' == err.code) err = utils.error(404);ocdTJ Holowaychukbefore adoptiond115798
lines 226–254why, one step back226227 // ditch content-disposition to prevent funky responses228 if (!self.headerSent) self.removeHeader('Content-Disposition');229230 // woot! callback available231 if (fn) return fn(err);232233 // lost in limbo if there's no callback234 if (self.headerSent) return;235236 return req.next(err);237 }238239 fn && fn();240 };241242 // transfer243 options.path = encodeURIComponent(path);244 send(this.req, this, next, options);245};246247/**248 * Transfer the file at the given `path` as an attachment.249 *250 * Optionally providing an alternate attachment `filename`,251 * and optional callback `fn(err)`. The callback is invoked252 * when the data transfer is complete, or when an error has253 * ocurred. Be sure to check `res.headerSent` if you plan to respond.254 *Added res.download() testsTJ Holowaychukbefore adoption5840b42
line 255why, one step back255 * This method uses `res.sendfile()`.Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 256why, one step back256 *ocdTJ Holowaychukbefore adoptiond115798
lines 257–269why, one step back257 * @param {String} path258 * @param {String|Function} filename or fn259 * @param {Function} fn260 * @api public261 */262263res.download = function(path, filename, fn){264 // support function as second arg265 if ('function' == typeof filename) {266 fn = filename;267 filename = null;268 }269Added res.download() testsTJ Holowaychukbefore adoption5840b42
lines 270–272why, one step back270 filename = filename || path;271 this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');272 return this.sendfile(path, fn);ocdTJ Holowaychukbefore adoptiond115798
lines 273–275why, one step back273};274275/**Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95
lines 276–277why, one step back276 * Set _Content-Type_ response header with `type` through `mime.lookup()`277 * when it does not contain "/", or set the Content-Type to `type` otherwise.ocdTJ Holowaychukbefore adoptiond115798
lines 278–280why, one step back278 *279 * Examples:280 *Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95
lines 281–284why, one step back281 * res.type('.html');282 * res.type('html');283 * res.type('json');284 * res.type('application/json');ocdTJ Holowaychukbefore adoptiond115798
lines 285–293why, one step back285 * res.type('png');286 *287 * @param {String} type288 * @return {ServerResponse} for chaining289 * @api public290 */291292res.contentType =293res.type = function(type){Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95
lines 294–296why, one step back294 return this.set('Content-Type', ~type.indexOf('/')295 ? type296 : mime.lookup(type));ocdTJ Holowaychukbefore adoptiond115798
lines 297–344why, one step back297};298299/**300 * Respond to the Acceptable formats using an `obj`301 * of mime-type callbacks.302 *303 * This method uses `req.accepted`, an array of304 * acceptable types ordered by their quality values.305 * When "Accept" is not present the _first_ callback306 * is invoked, otherwise the first match is used. When307 * no match is performed the server responds with308 * 406 "Not Acceptable".309 *310 * Content-Type is set for you, however if you choose311 * you may alter this within the callback using `res.type()`312 * or `res.set('Content-Type', ...)`.313 *314 * res.format({315 * 'text/plain': function(){316 * res.send('hey');317 * },318 * 319 * 'text/html': function(){320 * res.send('<p>hey</p>');321 * },322 * 323 * 'appliation/json': function(){324 * res.send({ message: 'hey' });325 * }326 * });327 *328 * In addition to canonicalized MIME types you may329 * also use extnames mapped to these types:330 *331 * res.format({332 * text: function(){333 * res.send('hey');334 * },335 * 336 * html: function(){337 * res.send('<p>hey</p>');338 * },339 * 340 * json: function(){341 * res.send({ message: 'hey' });342 * }343 * });344 *mention res.format() callbackTJ Holowaychukbefore adoptionfd42b5c
lines 345–350why, one step back345 * By default Express passes an `Error`346 * with a `.status` of 406 to `next(err)`347 * if a match is not made, however you may348 * provide an optional callback `fn` to349 * be invoked instead.350 *ocdTJ Holowaychukbefore adoptiond115798
line 351why, one step back351 * @param {Object} objmention res.format() callbackTJ Holowaychukbefore adoptionfd42b5c
line 352why, one step back352 * @param {Function} fnocdTJ Holowaychukbefore adoptiond115798
lines 353–356why, one step back353 * @return {ServerResponse} for chaining354 * @api public355 */356Fixed res.redirect() 406. Closes #1154TJ Holowaychukbefore adoption1311f2a
line 357why, one step back357res.format = function(obj, fn){ocdTJ Holowaychukbefore adoptiond115798
lines 358–360why, one step back358 var keys = Object.keys(obj)359 , req = this.req360 , next = req.nextAdded array support. Closes #1053TJ Holowaychukbefore adoption298899d
line 361why, one step back361 , key = req.accepts(keys);ocdTJ Holowaychukbefore adoptiond115798
line 362why, one step back362Added: `res.format()` sets Vary: AcceptTJ Holowaychukbefore adoption12e0878
lines 363–364why, one step back363 this.set('Vary', 'Accept');364ocdTJ Holowaychukbefore adoptiond115798
line 365why, one step back365 if (key) {Added array support. Closes #1053TJ Holowaychukbefore adoption298899d
line 366why, one step back366 this.set('Content-Type', normalizeType(key));ocdTJ Holowaychukbefore adoptiond115798
line 367why, one step back367 obj[key](req, this, next);Fixed res.redirect() 406. Closes #1154TJ Holowaychukbefore adoption1311f2a
lines 368–369why, one step back368 } else if (fn) {369 fn();ocdTJ Holowaychukbefore adoptiond115798
lines 370–372why, one step back370 } else {371 var err = new Error('Not Acceptable');372 err.status = 406;Added array support. Closes #1053TJ Holowaychukbefore adoption298899d
line 373why, one step back373 err.types = normalizeTypes(keys);ocdTJ Holowaychukbefore adoptiond115798
lines 374–388why, one step back374 next(err);375 }376377 return this;378};379380/**381 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.382 *383 * @param {String} filename384 * @return {ServerResponse}385 * @api public386 */387388res.attachment = function(filename){Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95
line 389why, one step back389 if (filename) this.type(extname(filename));ocdTJ Holowaychukbefore adoptiond115798
lines 390–404why, one step back390 this.set('Content-Disposition', filename391 ? 'attachment; filename="' + basename(filename) + '"'392 : 'attachment');393 return this;394};395396/**397 * Set header `field` to `val`, or pass398 * an object of of header fields.399 *400 * Examples:401 *402 * res.set('Accept', 'application/json');403 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });404 *docsTJ Holowaychukbefore adoption27b1b5e
lines 405–406why, one step back405 * Aliased as `res.header()`. 406 *ocdTJ Holowaychukbefore adoptiond115798
lines 407–412why, one step back407 * @param {String|Object} field408 * @param {String} val409 * @return {ServerResponse} for chaining410 * @api public411 */412Added `res.header()` and `req.header()` aliases for BCTJ Holowaychukbefore adoption5fa2f89
lines 413–414why, one step back413res.set = 414res.header = function(field, val){ocdTJ Holowaychukbefore adoptiond115798
line 415why, one step back415 if (2 == arguments.length) {Added: coerce `res.set()` values to stringsTJ Holowaychukbefore adoption67ddb42
line 416why, one step back416 this.setHeader(field, '' + val);ocdTJ Holowaychukbefore adoptiond115798
lines 417–418why, one step back417 } else {418 for (var key in field) {Added: coerce `res.set()` values to stringsTJ Holowaychukbefore adoption67ddb42
line 419why, one step back419 this.setHeader(key, '' + field[key]);ocdTJ Holowaychukbefore adoptiond115798
lines 420–458why, one step back420 }421 }422 return this;423};424425/**426 * Get value for header `field`.427 *428 * @param {String} field429 * @return {String}430 * @api public431 */432433res.get = function(field){434 return this.getHeader(field);435};436437/**438 * Clear cookie `name`.439 *440 * @param {String} name441 * @param {Object} options442 * @param {ServerResponse} for chaining443 * @api public444 */445446res.clearCookie = function(name, options){447 var opts = { expires: new Date(1), path: '/' };448 return this.cookie(name, '', options449 ? utils.merge(opts, options)450 : opts);451};452453/**454 * Set cookie `name` to `val`, with the given `options`.455 *456 * Options:457 *458 * - `maxAge` max-age in milliseconds, converted to `expires`Added { signed: true } option to res.cookie()TJ Holowaychukbefore adoption1150a88
line 459why, one step back459 * - `signed` sign the cookieocdTJ Holowaychukbefore adoptiond115798
lines 460–477why, one step back460 * - `path` defaults to "/"461 *462 * Examples:463 *464 * // "Remember Me" for 15 minutes465 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });466 *467 * // save as above468 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })469 *470 * @param {String} name471 * @param {String|Object} val472 * @param {Options} options473 * @api public474 */475476res.cookie = function(name, val, options){477 options = options || {};Added { signed: true } option to res.cookie()TJ Holowaychukbefore adoption1150a88
lines 478–480why, one step back478 var secret = this.req.secret;479 var signed = options.signed;480 if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');ocdTJ Holowaychukbefore adoptiond115798
line 481why, one step back481 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);Added { signed: true } option to res.cookie()TJ Holowaychukbefore adoption1150a88
line 482why, one step back482 if (signed) val = utils.sign(val, secret);ocdTJ Holowaychukbefore adoptiond115798
lines 483–484why, one step back483 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);484 if (null == options.path) options.path = '/';coerce res.cookie values to stringsTJ Holowaychukbefore adoptionebf60d2
line 485why, one step back485 this.set('Set-Cookie', cookie.serialize(name, String(val), options));ocdTJ Holowaychukbefore adoptiond115798
lines 486–501why, one step back486 return this;487};488489/**490 * Redirect to the given `url` with optional response `status`491 * defaulting to 302.492 *493 * The given `url` can also be the name of a mapped url, for494 * example by default express supports "back" which redirects495 * to the _Referrer_ or _Referer_ headers or "/".496 *497 * Examples:498 *499 * res.redirect('/foo/bar');500 * res.redirect('http://example.com');501 * res.redirect(301, 'http://example.com');added another res.redirect() exampleTJ Holowaychukbefore adoptionba413ee
line 502why, one step back502 * res.redirect('../login'); // /blog/post/1 -> /blog/loginocdTJ Holowaychukbefore adoptiond115798
lines 503–559why, one step back503 *504 * Mounting:505 *506 * When an application is mounted, and `res.redirect()`507 * is given a path that does _not_ lead with "/". For 508 * example suppose a "blog" app is mounted at "/blog",509 * the following redirect would result in "/blog/login":510 *511 * res.redirect('login');512 *513 * While the leading slash would result in a redirect to "/login":514 *515 * res.redirect('/login');516 *517 * @param {String} url518 * @param {Number} code519 * @api public520 */521522res.redirect = function(url){523 var app = this.app524 , req = this.req525 , head = 'HEAD' == req.method526 , status = 302527 , body;528529 // allow status / url530 if (2 == arguments.length) {531 status = url;532 url = arguments[1];533 }534535 // setup redirect map536 var map = { back: req.get('Referrer') || '/' };537538 // perform redirect539 url = map[url] || url;540541 // relative542 if (!~url.indexOf('://')) {543 var path = app.path();544545 // relative to path546 if (0 == url.indexOf('./') || 0 == url.indexOf('..')) {547 url = req.path + '/' + url;548 // relative to mount-point549 } else if ('/' != url[0]) {550 url = path + '/' + url;551 }552553 // Absolute554 var host = req.get('Host');555 url = req.protocol + '://' + host + url;556 }557558 // Support text/{plain,html} by default559 this.format({Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 560why, one step back560 text: function(){ocdTJ Holowaychukbefore adoptiond115798
lines 561–563why, one step back561 body = statusCodes[status] + '. Redirecting to ' + url;562 },563Added new dox API docsTJ Holowaychukbefore adoption7e81cad
line 564why, one step back564 html: function(){ocdTJ Holowaychukbefore adoptiond115798
lines 565–566why, one step back565 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';566 }Fixed res.redirect() 406. Closes #1154TJ Holowaychukbefore adoption1311f2a
lines 567–568why, one step back567 }, function(){568 body = '';ocdTJ Holowaychukbefore adoptiond115798
lines 569–573why, one step back569 })570571 // Respond572 this.statusCode = status;573 this.set('Location', url);Fixed res.redirect() 406. Closes #1154TJ Holowaychukbefore adoption1311f2a
line 574why, one step back574 this.set('Content-Length', Buffer.byteLength(body));ocdTJ Holowaychukbefore adoptiond115798
lines 575–624why, one step back575 this.end(head ? null : body);576};577578/**579 * Render `view` with the given `options` and optional callback `fn`.580 * When a callback function is given a response will _not_ be made581 * automatically, otherwise a response of _200_ and _text/html_ is given.582 *583 * Options:584 * 585 * - `status` Response status code (`res.statusCode`)586 * - `charset` Set the charset (`res.charset`)587 *588 * Reserved locals:589 *590 * - `cache` boolean hinting to the engine it should cache591 * - `filename` filename of the view being rendered592 *593 * @param {String} view594 * @param {Object|Function} options or callback function595 * @param {Function} fn596 * @api public597 */598599res.render = function(view, options, fn){600 var self = this601 , options = options || {}602 , req = this.req603 , app = req.app;604605 // support callback function as second arg606 if ('function' == typeof options) {607 fn = options, options = {};608 }609610 function render() {611 // merge res.locals612 options.locals = self.locals;613614 // default callback to respond615 fn = fn || function(err, str){616 if (err) return req.next(err);617 self.send(str);618 };619620 // render621 app.render(view, options, fn);622 }623624 // invoke view callbacksAdded res.locals.use(). Closes #1120TJ Holowaychukbefore adoptiondd33ef2
line 625why, one step back625 var callbacks = app.viewCallbacks.concat(self.viewCallbacks)ocdTJ Holowaychukbefore adoptiond115798
lines 626–647why, one step back626 , pending = callbacks.length627 , len = pending628 , done;629630 if (len) {631 for (var i = 0; i < len; ++i) {632 callbacks[i](req, self, function(err){633 if (done) return;634635 if (err) {636 req.next(err);637 done = true;638 return;639 }640641 --pending || render();642 });643 }644 } else {645 render();646 }647};