response.js
This file
Path
lib/response.js
450 lines · 10.6 KiB · JavaScript
Last changed by
fixed `res.sendfile()` 404 supportTj Holowaychukbefore adoptiond2df055
History of this fileTake it
The walk stopped after 200 commits: lines older than 70e6baf point at it.
misc refactoringTj Holowaychukbefore adoption70e6baf
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_CODESmisc refactoringTj Holowaychukbefore adoption70e6baf
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.misc refactoringTj Holowaychukbefore adoption70e6baf
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');misc refactoringTj Holowaychukbefore adoption70e6baf
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} bodymisc refactoringTj Holowaychukbefore adoption70e6baf
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
lines 42–47why, one step back42res.send = function(body){43 // allow status / body44 if (2 == arguments.length) {45 this.statusCode = body;46 body = arguments[1];47 }misc refactoringTj Holowaychukbefore adoption70e6baf
lines 48–49why, one step back4849 switch (typeof body) {Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 50why, one step back50 // response statusmisc refactoringTj Holowaychukbefore adoption70e6baf
line 51why, one step back51 case 'number':Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
lines 52–54why, one step back52 this.header('Content-Type') || this.contentType('.txt');53 this.statusCode = body;54 body = http.STATUS_CODES[body];misc refactoringTj Holowaychukbefore adoption70e6baf
line 55why, one step back55 break;Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 56why, one step back56 // string defaulting to htmlmisc refactoringTj Holowaychukbefore adoption70e6baf
lines 57–64why, one step back57 case 'string':58 if (!this.header('Content-Type')) {59 this.charset = this.charset || 'utf-8';60 this.contentType('.html');61 }62 break;63 case 'boolean':64 case 'object':Changed `res.send(null)` responds with empty stringTj Holowaychukbefore adoption376bedf
lines 65–67why, one step back65 if (null == body) {66 body = '';67 } else if (Buffer.isBuffer(body)) {Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 68why, one step back68 this.header('Content-Type') || this.contentType('.bin');misc refactoringTj Holowaychukbefore adoption70e6baf
line 69why, one step back69 } else {Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 70why, one step back70 return this.json(body);misc refactoringTj Holowaychukbefore adoption70e6baf
lines 71–75why, one step back71 }72 break;73 }7475 // populate Content-LengthFixed [23]04 supportTj Holowaychukbefore adoption5ac5352
line 76why, one step back76 if (undefined !== body && !this.header('Content-Length')) {misc refactoringTj Holowaychukbefore adoption70e6baf
lines 77–82why, one step back77 this.header('Content-Length', Buffer.isBuffer(body)78 ? body.length79 : Buffer.byteLength(body));80 }8182 // strip irrelevant headersChanged `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 83why, one step back83 if (204 == this.statusCode || 304 == this.statusCode) {misc refactoringTj Holowaychukbefore adoption70e6baf
lines 84–85why, one step back84 this.removeHeader('Content-Type');85 this.removeHeader('Content-Length');Fixed 204 / 304 responsesTj Holowaychukbefore adoptionc631eb4
line 86why, one step back86 body = '';misc refactoringTj Holowaychukbefore adoption70e6baf
lines 87–90why, one step back87 }8889 // respond90 this.end('HEAD' == this.req.method ? undefined : body);Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 91–94why, one step back91 return this;92};9394/**Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 95why, one step back95 * Send JSON response.Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 96–100why, one step back96 *97 * Examples:98 *99 * res.json(null);100 * res.json({ user: 'tj' });Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
lines 101–102why, one step back101 * res.json(500, 'oh noes!');102 * res.json(404, 'I dont have that');Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
line 103why, one step back103 *Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 104why, one step back104 * @param {Mixed} obj or statusMerge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 105–109why, one step back105 * @param {Mixed} obj106 * @return {ServerResponse}107 * @api public108 */109Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
lines 110–116why, one step back110res.json = function(obj){111 // allow status / body112 if (2 == arguments.length) {113 this.statusCode = obj;114 obj = arguments[1];115 }116Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 117–120why, one step back117 var body = JSON.stringify(obj)118 , callback = this.req.query.callback119 , jsonp = this.app.enabled('jsonp callback');120Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 121–122why, one step back121 this.charset = this.charset || 'utf-8';122 this.header('Content-Type', 'application/json');Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 123–125why, one step back123124 if (callback && jsonp) {125 this.header('Content-Type', 'text/javascript');Revert "removed jsonp stripping"Tj Holowaychukbefore adoption60d16ea
line 126why, one step back126 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 127–128why, one step back127 }128Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f
line 129why, one step back129 return this.send(body);misc refactoringTj Holowaychukbefore adoption70e6baf
lines 130–131why, one step back130};131docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 132–139why, one step back132/**133 * Set status `code`.134 *135 * @param {Number} code136 * @return {ServerResponse}137 * @api public138 */139Added chainable res.status(code)Tj Holowaychukbefore adoptionb04be51
lines 140–144why, one step back140res.status = function(code){141 this.statusCode = code;142 return this;143};144misc refactoringTj Holowaychukbefore adoption70e6baf
line 145why, one step back145/**refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be
lines 146–149why, one step back146 * Transfer the file at the given `path`.147 * 148 * Automatically sets the _Content-Type_ response header field.149 * The callback `fn(err)` is invoked when the transfer is completemake `res.sendfile()` more like `res.download()`. Closes #774Tj Holowaychukbefore adoption7a476fc
line 150why, one step back150 * or when an error occurs. Be sure to check `res.sentHeader`refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be
lines 151–152why, one step back151 * if you wish to attempt responding, as the header and some data152 * may have already been transferred.misc refactoringTj Holowaychukbefore adoption70e6baf
lines 153–165why, one step back153 *154 * Options:155 *156 * - `maxAge` defaulting to 0157 * - `root` root directory for relative filenames158 *159 * @param {String} path160 * @param {Object|Function} options or fn161 * @param {Function} fn162 * @api public163 */164165res.sendfile = function(path, options, fn){refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be
line 166why, one step back166 var self = thisfixed `res.sendfile()` 404 supportTj Holowaychukbefore adoptiond2df055
line 167why, one step back167 , req = self.reqrefactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be
lines 168–169why, one step back168 , next = this.req.next169 , options = options || {};misc refactoringTj Holowaychukbefore adoption70e6baf
lines 170–176why, one step back170171 // support function as second arg172 if ('function' == typeof options) {173 fn = options;174 options = {};175 }176refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be
lines 177–179why, one step back177 // callback178 options.callback = function(err){179 // TODO: remove when node adds thismake `res.sendfile()` more like `res.download()`. Closes #774Tj Holowaychukbefore adoption7a476fc
lines 180–186why, one step back180 self.sentHeader = !! self._header;181182 // error183 if (err) {184 // ditch content-disposition to prevent funky responses185 if (!self.sentHeader) self.removeHeader('Content-Disposition');186fixed `res.sendfile()` 404 supportTj Holowaychukbefore adoptiond2df055
lines 187–189why, one step back187 // not found188 if ('ENOENT' == err.code) return req.next();189make `res.sendfile()` more like `res.download()`. Closes #774Tj Holowaychukbefore adoption7a476fc
lines 190–195why, one step back190 // lost in limbo if there's no callback191 if (self.sentHeader) return fn && fn(err);192193 // callback available194 if (fn) return fn(err);195fixed `res.sendfile()` 404 supportTj Holowaychukbefore adoptiond2df055
line 196why, one step back196 return req.next(err);make `res.sendfile()` more like `res.download()`. Closes #774Tj Holowaychukbefore adoption7a476fc
lines 197–199why, one step back197 }198199 fn && fn();refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be
lines 200–202why, one step back200 };201202 // transfermisc refactoringTj Holowaychukbefore adoption70e6baf
lines 203–207why, one step back203 options.path = encodeURIComponent(path);204 send(this.req, this, next, options);205};206207/**build `res.download()` on top of `res.sendfile()`Tj Holowaychukbefore adoptiond3ccdbc
lines 208–231why, one step back208 * Transfer the file at the given `path` as an attachment.209 *210 * Optionally providing an alternate attachment `filename`,211 * and optional callback `fn(err)`. The callback is invoked212 * when the data transfer is complete, or when an error has213 * ocurred. Be sure to check `res.sendHeader` if you plan to respond.214 *215 * @param {String} path216 * @param {String|Function} filename or fn217 * @param {Function} fn218 * @api public219 */220221res.download = function(path, filename, fn){222 // support function as second arg223 if ('function' == typeof filename) {224 fn = filename;225 filename = null;226 }227228 return this.attachment(filename || path).sendfile(path, fn);229};230231/**misc refactoringTj Holowaychukbefore adoption70e6baf
lines 232–245why, one step back232 * Set _Content-Type_ response header passed through `mime.lookup()`.233 *234 * Examples:235 *236 * var filename = 'path/to/image.png';237 * res.contentType(filename);238 * // res.headers['Content-Type'] is now "image/png"239 *240 * res.contentType('.html');241 * res.contentType('html');242 * res.contentType('json');243 * res.contentType('png');244 *245 * @param {String} typedocsTj Holowaychukbefore adoptionbb9d505
line 246why, one step back246 * @return {ServerResponse} for chainingmisc refactoringTj Holowaychukbefore adoption70e6baf
lines 247–270why, one step back247 * @api public248 */249250res.contentType = function(type){251 return this.header('Content-Type', mime.lookup(type));252};253254/**255 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.256 *257 * @param {String} filename258 * @return {ServerResponse}259 * @api public260 */261262res.attachment = function(filename){263 if (filename) this.contentType(filename);264 this.header('Content-Disposition', filename265 ? 'attachment; filename="' + basename(filename) + '"'266 : 'attachment');267 return this;268};269270/**Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
line 271why, one step back271 * Set header `field` to `val`.Added `res.set(field, val)` as an alternative to `res.header()`Tj Holowaychukbefore adoption19a1a22
line 272why, one step back272 *Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
line 273why, one step back273 * @param {String} fieldAdded `res.set(field, val)` as an alternative to `res.header()`Tj Holowaychukbefore adoption19a1a22
lines 274–278why, one step back274 * @param {String} val275 * @return {ServerResponse} for chaining276 * @api public277 */278Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
lines 279–280why, one step back279res.set = function(field, val){280 this.setHeader(field, val);Added `res.set(field, val)` as an alternative to `res.header()`Tj Holowaychukbefore adoption19a1a22
lines 281–284why, one step back281 return this;282};283284/**Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
line 285why, one step back285 * Get value for header `field`.misc refactoringTj Holowaychukbefore adoption70e6baf
line 286why, one step back286 *Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
lines 287–298why, one step back287 * @param {String} field288 * @return {String}289 * @api public290 */291292res.get = function(field){293 return this.getHeader(field);294};295296/**297 * Set or get response header `field` with optional `val`.298 *misc refactoringTj Holowaychukbefore adoption70e6baf
lines 299–300why, one step back299 * @param {String} name300 * @param {String} valMerge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
line 301why, one step back301 * @return {ServerResponse} for chainingmisc refactoringTj Holowaychukbefore adoption70e6baf
lines 302–304why, one step back302 * @api public303 */304Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
lines 305–307why, one step back305res.header = function(field, val){306 if (1 == arguments.length) return this.getHeader(field);307 this.setHeader(field, val);Refactored `res.header()`Tj Holowaychukbefore adoption54d3751
line 308why, one step back308 return this;misc refactoringTj Holowaychukbefore adoption70e6baf
lines 309–315why, one step back309};310311/**312 * Clear cookie `name`.313 *314 * @param {String} name315 * @param {Object} optionsChanged `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8
line 316why, one step back316 * @param {ServerResponse} for chainingmisc refactoringTj Holowaychukbefore adoption70e6baf
lines 317–321why, one step back317 * @api public318 */319320res.clearCookie = function(name, options){321 var opts = { expires: new Date(1) };Changed `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8
line 322why, one step back322 return this.cookie(name, '', optionsmisc refactoringTj Holowaychukbefore adoption70e6baf
lines 323–332why, one step back323 ? utils.merge(options, opts)324 : opts);325};326327/**328 * Set cookie `name` to `val`, with the given `options`.329 *330 * Options:331 *332 * - `maxAge` max-age in milliseconds, converted to `expires`Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b
line 333why, one step back333 * - `path` defaults to the "basepath" setting which is typically "/"misc refactoringTj Holowaychukbefore adoption70e6baf
lines 334–351why, one step back334 *335 * Examples:336 *337 * // "Remember Me" for 15 minutes338 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });339 *340 * // save as above341 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })342 *343 * @param {String} name344 * @param {String} val345 * @param {Options} options346 * @api public347 */348349res.cookie = function(name, val, options){350 options = options || {};351 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b
line 352why, one step back352 if (undefined === options.path) options.path = this.app.set('basepath');misc refactoringTj Holowaychukbefore adoption70e6baf
lines 353–354why, one step back353 var cookie = utils.serializeCookie(name, val, options);354 this.header('Set-Cookie', cookie);Changed `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8
line 355why, one step back355 return this;misc refactoringTj Holowaychukbefore adoption70e6baf
lines 356–364why, one step back356};357358/**359 * Redirect to the given `url` with optional response `status`360 * defauling to 302.361 *362 * The given `url` can also be the name of a mapped url, for363 * example by default express supports "back" which redirects364 * to the _Referrer_ or _Referer_ headers or the application'sMerged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b
lines 365–366why, one step back365 * "basepath" setting. Express also supports "basepath" out of the box,366 * which can be set via `app.set('basepath', '/blog');`.misc refactoringTj Holowaychukbefore adoption70e6baf
lines 367–404why, one step back367 *368 * Redirect Mapping:369 * 370 * To extend the redirect mapping capabilities that Express provides,371 * we may use the `app.redirect()` method:372 * 373 * app.redirect('google', 'http://google.com');374 * 375 * Now in a route we may call:376 *377 * res.redirect('google');378 *379 * We may also map dynamic redirects:380 *381 * app.redirect('comments', function(req, res){382 * return '/post/' + req.params.id + '/comments';383 * });384 *385 * So now we may do the following, and the redirect will dynamically adjust to386 * the context of the request. If we called this route with _GET /post/12_ our387 * redirect _Location_ would be _/post/12/comments_.388 *389 * app.get('/post/:id', function(req, res){390 * res.redirect('comments');391 * });392 *393 * Unless an absolute `url` is given, the app's mount-point394 * will be respected. For example if we redirect to `/posts`,395 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.396 *397 * @param {String} url398 * @param {Number} code399 * @api public400 */401402res.redirect = function(url, status){403 var app = this.app404 , req = this.reqMerged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b
line 405why, one step back405 , base = app.set('basepath') || app.routemisc refactoringTj Holowaychukbefore adoption70e6baf
lines 406–428why, one step back406 , status = status || 302407 , body;408409 // Setup redirect map410 var map = {411 back: req.header('Referrer', base)412 , home: base413 };414415 // Support custom redirect map416 map.__proto__ = app.redirects;417418 // Attempt mapped redirect419 var mapped = 'function' == typeof map[url]420 ? map[url](req, this)421 : map[url];422423 // Perform redirect424 url = mapped || url;425426 // Relative427 if (!~url.indexOf('://')) {428 // Respect mount-pointMerged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b
line 429why, one step back429 if ('/' != base && 0 != url.indexOf(base)) url = base + url;misc refactoringTj Holowaychukbefore adoption70e6baf
lines 430–438why, one step back430431 // Absolute432 var host = req.headers.host433 , tls = req.connection.encrypted;434 url = 'http' + (tls ? 's' : '') + '://' + host + url;435 }436437 // Support text/{plain,html} by default438 if (req.accepts('html')) {refactored `res.redirect()` slightlyTj Holowaychukbefore adoption6bd5182
line 439why, one step back439 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';misc refactoringTj Holowaychukbefore adoption70e6baf
lines 440–441why, one step back440 this.header('Content-Type', 'text/html');441 } else {refactored `res.redirect()` slightlyTj Holowaychukbefore adoption6bd5182
line 442why, one step back442 body = statusCodes[status] + '. Redirecting to ' + url;misc refactoringTj Holowaychukbefore adoption70e6baf
lines 443–450why, one step back443 this.header('Content-Type', 'text/plain');444 }445446 // Respond447 this.statusCode = status;448 this.header('Location', url);449 this.end(body);450};