response.js
This file
Path
lib/response.js
453 lines · 10.6 KiB · JavaScript
Last changed by
refactored `res.send()`Tj Holowaychukbefore adoption2c734e2
History of this fileTake it
The walk stopped after 200 commits: lines older than 44eae73 point at it.
Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 1–16why, one step back12/*!3 * Express - response4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var fs = require('fs')13 , http = require('http')14 , path = require('path')15 , connect = require('connect')16 , utils = connect.utilsrefactored `res.redirect()` slightlyTj Holowaychukbefore adoption6bd5182
line 17why, one step back17 , statusCodes = http.STATUS_CODESRelease 2.3.7Tj Holowaychukbefore adoption44eae73
lines 18–25why, one step back18 , parseRange = require('./utils').parseRange19 , res = http.ServerResponse.prototype20 , send = connect.static.send21 , mime = require('mime')22 , basename = path.basename23 , join = path.join;2425/**Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 26why, one step back26 * Send a response.Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 27–32why, one step back27 *28 * Examples:29 *30 * res.send(new Buffer('wahoo'));31 * res.send({ some: 'json' });32 * res.send('<p>some html</p>');Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 33why, one step back33 * res.send(404, 'Sorry, cant find that');Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 34–35why, one step back34 * res.send(404);35 *Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
lines 36–37why, one step back36 * @param {Mixed} body or status37 * @param {Mixed} bodyRelease 2.3.7Tj Holowaychukbefore adoption44eae73
lines 38–41why, one step back38 * @return {ServerResponse}39 * @api public40 */41Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 42why, one step back42res.send = function(body){refactored `res.send()`Tj Holowaychukbefore adoption2c734e2
lines 43–45why, one step back43 var req = this.req44 , head = 'HEAD' == req.method;45Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
lines 46–50why, one step back46 // allow status / body47 if (2 == arguments.length) {48 this.statusCode = body;49 body = arguments[1];50 }Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 51–52why, one step back5152 switch (typeof body) {Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 53why, one step back53 // response statusRelease 2.3.7Tj Holowaychukbefore adoption44eae73
line 54why, one step back54 case 'number':Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
lines 55–57why, one step back55 this.header('Content-Type') || this.contentType('.txt');56 this.statusCode = body;57 body = http.STATUS_CODES[body];Release 2.3.7Tj Holowaychukbefore adoption44eae73
line 58why, one step back58 break;Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 59why, one step back59 // string defaulting to htmlRelease 2.3.7Tj Holowaychukbefore adoption44eae73
lines 60–67why, one step back60 case 'string':61 if (!this.header('Content-Type')) {62 this.charset = this.charset || 'utf-8';63 this.contentType('.html');64 }65 break;66 case 'boolean':67 case 'object':Changed `res.send(null)` responds with empty stringTj Holowaychukbefore adoption376bedf
lines 68–70why, one step back68 if (null == body) {69 body = '';70 } else if (Buffer.isBuffer(body)) {Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 71why, one step back71 this.header('Content-Type') || this.contentType('.bin');Release 2.3.7Tj Holowaychukbefore adoption44eae73
line 72why, one step back72 } else {Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 73why, one step back73 return this.json(body);Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 74–78why, one step back74 }75 break;76 }7778 // populate Content-LengthFixed [23]04 supportTj Holowaychukbefore adoption5ac5352
line 79why, one step back79 if (undefined !== body && !this.header('Content-Length')) {Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 80–85why, one step back80 this.header('Content-Length', Buffer.isBuffer(body)81 ? body.length82 : Buffer.byteLength(body));83 }8485 // strip irrelevant headersChanged `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 86why, one step back86 if (204 == this.statusCode || 304 == this.statusCode) {Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 87–88why, one step back87 this.removeHeader('Content-Type');88 this.removeHeader('Content-Length');Fixed 204 / 304 responsesTj Holowaychukbefore adoptionc631eb4
line 89why, one step back89 body = '';Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 90–92why, one step back90 }9192 // respondrefactored `res.send()`Tj Holowaychukbefore adoption2c734e2
line 93why, one step back93 this.end(head ? null : body);Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 94–97why, one step back94 return this;95};9697/**Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 98why, one step back98 * Send JSON response.Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 99–103why, one step back99 *100 * Examples:101 *102 * res.json(null);103 * res.json({ user: 'tj' });Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
lines 104–105why, one step back104 * res.json(500, 'oh noes!');105 * res.json(404, 'I dont have that');Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
line 106why, one step back106 *Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 107why, one step back107 * @param {Mixed} obj or statusMerge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 108–112why, one step back108 * @param {Mixed} obj109 * @return {ServerResponse}110 * @api public111 */112Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
lines 113–119why, one step back113res.json = function(obj){114 // allow status / body115 if (2 == arguments.length) {116 this.statusCode = obj;117 obj = arguments[1];118 }119Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 120–123why, one step back120 var body = JSON.stringify(obj)121 , callback = this.req.query.callback122 , jsonp = this.app.enabled('jsonp callback');123Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 124–125why, one step back124 this.charset = this.charset || 'utf-8';125 this.header('Content-Type', 'application/json');Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 126–128why, one step back126127 if (callback && jsonp) {128 this.header('Content-Type', 'text/javascript');Revert "removed jsonp stripping"Tj Holowaychukbefore adoption60d16ea
line 129why, one step back129 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 130–131why, one step back130 }131Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 132why, one step back132 return this.send(body);Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 133–134why, one step back133};134docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 135–142why, one step back135/**136 * Set status `code`.137 *138 * @param {Number} code139 * @return {ServerResponse}140 * @api public141 */142Added chainable res.status(code)Tj Holowaychukbefore adoptionb04be51
lines 143–147why, one step back143res.status = function(code){144 this.statusCode = code;145 return this;146};147Release 2.3.7Tj Holowaychukbefore adoption44eae73
line 148why, one step back148/**refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be
lines 149–152why, one step back149 * Transfer the file at the given `path`.150 * 151 * Automatically sets the _Content-Type_ response header field.152 * The callback `fn(err)` is invoked when the transfer is completemake `res.sendfile()` more like `res.download()`. Closes #774Tj Holowaychukbefore adoption7a476fc
line 153why, one step back153 * or when an error occurs. Be sure to check `res.sentHeader`refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be
lines 154–155why, one step back154 * if you wish to attempt responding, as the header and some data155 * may have already been transferred.Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 156–168why, one step back156 *157 * Options:158 *159 * - `maxAge` defaulting to 0160 * - `root` root directory for relative filenames161 *162 * @param {String} path163 * @param {Object|Function} options or fn164 * @param {Function} fn165 * @api public166 */167168res.sendfile = function(path, options, fn){refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be
line 169why, one step back169 var self = thisfixed `res.sendfile()` 404 supportTj Holowaychukbefore adoptiond2df055
line 170why, one step back170 , req = self.reqrefactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be
lines 171–172why, one step back171 , next = this.req.next172 , options = options || {};Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 173–179why, one step back173174 // support function as second arg175 if ('function' == typeof options) {176 fn = options;177 options = {};178 }179refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be
lines 180–182why, one step back180 // callback181 options.callback = function(err){182 // TODO: remove when node adds thismake `res.sendfile()` more like `res.download()`. Closes #774Tj Holowaychukbefore adoption7a476fc
lines 183–189why, one step back183 self.sentHeader = !! self._header;184185 // error186 if (err) {187 // ditch content-disposition to prevent funky responses188 if (!self.sentHeader) self.removeHeader('Content-Disposition');189fixed `res.sendfile()` 404 supportTj Holowaychukbefore adoptiond2df055
lines 190–192why, one step back190 // not found191 if ('ENOENT' == err.code) return req.next();192make `res.sendfile()` more like `res.download()`. Closes #774Tj Holowaychukbefore adoption7a476fc
lines 193–198why, one step back193 // lost in limbo if there's no callback194 if (self.sentHeader) return fn && fn(err);195196 // callback available197 if (fn) return fn(err);198fixed `res.sendfile()` 404 supportTj Holowaychukbefore adoptiond2df055
line 199why, one step back199 return req.next(err);make `res.sendfile()` more like `res.download()`. Closes #774Tj Holowaychukbefore adoption7a476fc
lines 200–202why, one step back200 }201202 fn && fn();refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be
lines 203–205why, one step back203 };204205 // transferRelease 2.3.7Tj Holowaychukbefore adoption44eae73
lines 206–210why, one step back206 options.path = encodeURIComponent(path);207 send(this.req, this, next, options);208};209210/**build `res.download()` on top of `res.sendfile()`Tj Holowaychukbefore adoptiond3ccdbc
lines 211–234why, one step back211 * Transfer the file at the given `path` as an attachment.212 *213 * Optionally providing an alternate attachment `filename`,214 * and optional callback `fn(err)`. The callback is invoked215 * when the data transfer is complete, or when an error has216 * ocurred. Be sure to check `res.sendHeader` if you plan to respond.217 *218 * @param {String} path219 * @param {String|Function} filename or fn220 * @param {Function} fn221 * @api public222 */223224res.download = function(path, filename, fn){225 // support function as second arg226 if ('function' == typeof filename) {227 fn = filename;228 filename = null;229 }230231 return this.attachment(filename || path).sendfile(path, fn);232};233234/**Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 235–248why, one step back235 * Set _Content-Type_ response header passed through `mime.lookup()`.236 *237 * Examples:238 *239 * var filename = 'path/to/image.png';240 * res.contentType(filename);241 * // res.headers['Content-Type'] is now "image/png"242 *243 * res.contentType('.html');244 * res.contentType('html');245 * res.contentType('json');246 * res.contentType('png');247 *248 * @param {String} typedocsTj Holowaychukbefore adoptionbb9d505
line 249why, one step back249 * @return {ServerResponse} for chainingRelease 2.3.7Tj Holowaychukbefore adoption44eae73
lines 250–273why, one step back250 * @api public251 */252253res.contentType = function(type){254 return this.header('Content-Type', mime.lookup(type));255};256257/**258 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.259 *260 * @param {String} filename261 * @return {ServerResponse}262 * @api public263 */264265res.attachment = function(filename){266 if (filename) this.contentType(filename);267 this.header('Content-Disposition', filename268 ? 'attachment; filename="' + basename(filename) + '"'269 : 'attachment');270 return this;271};272273/**Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
line 274why, one step back274 * Set header `field` to `val`.Added `res.set(field, val)` as an alternative to `res.header()`Tj Holowaychukbefore adoption19a1a22
line 275why, one step back275 *Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
line 276why, one step back276 * @param {String} fieldAdded `res.set(field, val)` as an alternative to `res.header()`Tj Holowaychukbefore adoption19a1a22
lines 277–281why, one step back277 * @param {String} val278 * @return {ServerResponse} for chaining279 * @api public280 */281Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
lines 282–283why, one step back282res.set = function(field, val){283 this.setHeader(field, val);Added `res.set(field, val)` as an alternative to `res.header()`Tj Holowaychukbefore adoption19a1a22
lines 284–287why, one step back284 return this;285};286287/**Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
line 288why, one step back288 * Get value for header `field`.Release 2.3.7Tj Holowaychukbefore adoption44eae73
line 289why, one step back289 *Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
lines 290–301why, one step back290 * @param {String} field291 * @return {String}292 * @api public293 */294295res.get = function(field){296 return this.getHeader(field);297};298299/**300 * Set or get response header `field` with optional `val`.301 *Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 302–303why, one step back302 * @param {String} name303 * @param {String} valMerge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
line 304why, one step back304 * @return {ServerResponse} for chainingRelease 2.3.7Tj Holowaychukbefore adoption44eae73
lines 305–307why, one step back305 * @api public306 */307Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
lines 308–310why, one step back308res.header = function(field, val){309 if (1 == arguments.length) return this.getHeader(field);310 this.setHeader(field, val);Refactored `res.header()`Tj Holowaychukbefore adoption54d3751
line 311why, one step back311 return this;Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 312–318why, one step back312};313314/**315 * Clear cookie `name`.316 *317 * @param {String} name318 * @param {Object} optionsChanged `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8
line 319why, one step back319 * @param {ServerResponse} for chainingRelease 2.3.7Tj Holowaychukbefore adoption44eae73
lines 320–324why, one step back320 * @api public321 */322323res.clearCookie = function(name, options){324 var opts = { expires: new Date(1) };Changed `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8
line 325why, one step back325 return this.cookie(name, '', optionsRelease 2.3.7Tj Holowaychukbefore adoption44eae73
lines 326–335why, one step back326 ? utils.merge(options, opts)327 : opts);328};329330/**331 * Set cookie `name` to `val`, with the given `options`.332 *333 * Options:334 *335 * - `maxAge` max-age in milliseconds, converted to `expires`Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b
line 336why, one step back336 * - `path` defaults to the "basepath" setting which is typically "/"Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 337–354why, one step back337 *338 * Examples:339 *340 * // "Remember Me" for 15 minutes341 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });342 *343 * // save as above344 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })345 *346 * @param {String} name347 * @param {String} val348 * @param {Options} options349 * @api public350 */351352res.cookie = function(name, val, options){353 options = options || {};354 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b
line 355why, one step back355 if (undefined === options.path) options.path = this.app.set('basepath');Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 356–357why, one step back356 var cookie = utils.serializeCookie(name, val, options);357 this.header('Set-Cookie', cookie);Changed `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8
line 358why, one step back358 return this;Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 359–367why, one step back359};360361/**362 * Redirect to the given `url` with optional response `status`363 * defauling to 302.364 *365 * The given `url` can also be the name of a mapped url, for366 * example by default express supports "back" which redirects367 * to the _Referrer_ or _Referer_ headers or the application'sMerged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b
lines 368–369why, one step back368 * "basepath" setting. Express also supports "basepath" out of the box,369 * which can be set via `app.set('basepath', '/blog');`.Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 370–407why, one step back370 *371 * Redirect Mapping:372 * 373 * To extend the redirect mapping capabilities that Express provides,374 * we may use the `app.redirect()` method:375 * 376 * app.redirect('google', 'http://google.com');377 * 378 * Now in a route we may call:379 *380 * res.redirect('google');381 *382 * We may also map dynamic redirects:383 *384 * app.redirect('comments', function(req, res){385 * return '/post/' + req.params.id + '/comments';386 * });387 *388 * So now we may do the following, and the redirect will dynamically adjust to389 * the context of the request. If we called this route with _GET /post/12_ our390 * redirect _Location_ would be _/post/12/comments_.391 *392 * app.get('/post/:id', function(req, res){393 * res.redirect('comments');394 * });395 *396 * Unless an absolute `url` is given, the app's mount-point397 * will be respected. For example if we redirect to `/posts`,398 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.399 *400 * @param {String} url401 * @param {Number} code402 * @api public403 */404405res.redirect = function(url, status){406 var app = this.app407 , req = this.reqMerged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b
line 408why, one step back408 , base = app.set('basepath') || app.routeRelease 2.3.7Tj Holowaychukbefore adoption44eae73
lines 409–431why, one step back409 , status = status || 302410 , body;411412 // Setup redirect map413 var map = {414 back: req.header('Referrer', base)415 , home: base416 };417418 // Support custom redirect map419 map.__proto__ = app.redirects;420421 // Attempt mapped redirect422 var mapped = 'function' == typeof map[url]423 ? map[url](req, this)424 : map[url];425426 // Perform redirect427 url = mapped || url;428429 // Relative430 if (!~url.indexOf('://')) {431 // Respect mount-pointMerged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b
line 432why, one step back432 if ('/' != base && 0 != url.indexOf(base)) url = base + url;Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 433–441why, one step back433434 // Absolute435 var host = req.headers.host436 , tls = req.connection.encrypted;437 url = 'http' + (tls ? 's' : '') + '://' + host + url;438 }439440 // Support text/{plain,html} by default441 if (req.accepts('html')) {refactored `res.redirect()` slightlyTj Holowaychukbefore adoption6bd5182
line 442why, one step back442 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 443–444why, one step back443 this.header('Content-Type', 'text/html');444 } else {refactored `res.redirect()` slightlyTj Holowaychukbefore adoption6bd5182
line 445why, one step back445 body = statusCodes[status] + '. Redirecting to ' + url;Release 2.3.7Tj Holowaychukbefore adoption44eae73
lines 446–453why, one step back446 this.header('Content-Type', 'text/plain');447 }448449 // Respond450 this.statusCode = status;451 this.header('Location', url);452 this.end(body);453};