response.js
This file
Path
lib/response.js
629 lines · 14.0 KiB · JavaScript
Last changed by
renamed `res.respondTo()` to `res.format()`TJ Holowaychukbefore adoptionffcaa04
History of this fileTake it
The walk stopped after 200 commits: lines older than f42ce5b point at it.
qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
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.utilsAdded `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25
line 17why, one step back17 , accept = require('./utils').acceptqs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 18–22why, one step back18 , statusCodes = http.STATUS_CODES19 , send = connect.static.send20 , mime = require('mime')21 , basename = path.basename22 , join = path.join;no longer manipulate the req/res protos directlyTj Holowaychukbefore adoptiond249868
lines 23–30why, one step back2324/**25 * Response prototype.26 */2728var res = module.exports = {29 __proto__: http.ServerResponse.prototype30};qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 31–32why, one step back3132/**miscTj Holowaychukbefore adoption61ce6c5
lines 33–45why, one step back33 * Set status `code`.34 *35 * @param {Number} code36 * @return {ServerResponse}37 * @api public38 */3940res.status = function(code){41 this.statusCode = code;42 return this;43};4445/**Added res.cache() methodTj Holowaychukbefore adoptione21a79d
line 46why, one step back46 * Set Cache-Control to the given `type` and `options`.Added res.cache(str)Tj Holowaychukbefore adoptioncaec590
line 47why, one step back47 *docsTj Holowaychukbefore adoptionbf87d62
lines 48–51why, one step back48 * Options:49 *50 * - `maxAge` in milliseconds51 *Added res.cache() methodTj Holowaychukbefore adoptione21a79d
lines 52–53why, one step back52 * @param {String} type53 * @param {Object} optionsAdded res.cache(str)Tj Holowaychukbefore adoptioncaec590
lines 54–57why, one step back54 * @return {ServerResponse}55 * @api public56 */57Added res.cache() methodTj Holowaychukbefore adoptione21a79d
lines 58–62why, one step back58res.cache = function(type, options){59 var val = type;60 options = options || {};61 if (options.maxAge) val += ', max-age=' + (options.maxAge / 1000); 62 return this.set('Cache-Control', val);Added res.cache(str)Tj Holowaychukbefore adoptioncaec590
lines 63–65why, one step back63};6465/**qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 66–94why, one step back66 * Send a response.67 *68 * Examples:69 *70 * res.send(new Buffer('wahoo'));71 * res.send({ some: 'json' });72 * res.send('<p>some html</p>');73 * res.send(404, 'Sorry, cant find that');74 * res.send(404);75 *76 * @param {Mixed} body or status77 * @param {Mixed} body78 * @return {ServerResponse}79 * @api public80 */8182res.send = function(body){83 var req = this.req84 , head = 'HEAD' == req.method;8586 // allow status / body87 if (2 == arguments.length) {88 this.statusCode = body;89 body = arguments[1];90 }9192 switch (typeof body) {93 // response status94 case 'number':utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 95why, one step back95 this.get('Content-Type') || this.contentType('.txt');qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 96–100why, one step back96 this.statusCode = body;97 body = http.STATUS_CODES[body];98 break;99 // string defaulting to html100 case 'string':utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 101why, one step back101 if (!this.get('Content-Type')) {qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 102–110why, one step back102 this.charset = this.charset || 'utf-8';103 this.contentType('.html');104 }105 break;106 case 'boolean':107 case 'object':108 if (null == body) {109 body = '';110 } else if (Buffer.isBuffer(body)) {utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 111why, one step back111 this.get('Content-Type') || this.contentType('.bin');qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 112–118why, one step back112 } else {113 return this.json(body);114 }115 break;116 }117118 // populate Content-Lengthutilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
lines 119–120why, one step back119 if (undefined !== body && !this.get('Content-Length')) {120 this.set('Content-Length', Buffer.isBuffer(body)qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 121–159why, one step back121 ? body.length122 : Buffer.byteLength(body));123 }124125 // strip irrelevant headers126 if (204 == this.statusCode || 304 == this.statusCode) {127 this.removeHeader('Content-Type');128 this.removeHeader('Content-Length');129 body = '';130 }131132 // respond133 this.end(head ? null : body);134 return this;135};136137/**138 * Send JSON response.139 *140 * Examples:141 *142 * res.json(null);143 * res.json({ user: 'tj' });144 * res.json(500, 'oh noes!');145 * res.json(404, 'I dont have that');146 *147 * @param {Mixed} obj or status148 * @param {Mixed} obj149 * @return {ServerResponse}150 * @api public151 */152153res.json = function(obj){154 // allow status / body155 if (2 == arguments.length) {156 this.statusCode = obj;157 obj = arguments[1];158 }159Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa
lines 160–165why, one step back160 var settings = this.app.settings161 , jsonp = settings['jsonp callback']162 , replacer = settings['json replacer']163 , spaces = settings['json spaces']164 , body = JSON.stringify(obj, replacer, spaces)165 , callback = this.req.query.callback;qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 166–167why, one step back166167 this.charset = this.charset || 'utf-8';utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 168why, one step back168 this.set('Content-Type', 'application/json');qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 169–170why, one step back169170 if (callback && jsonp) {utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 171why, one step back171 this.set('Content-Type', 'text/javascript');qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 172–212why, one step back172 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';173 }174175 return this.send(body);176};177178/**179 * Transfer the file at the given `path`.180 * 181 * Automatically sets the _Content-Type_ response header field.182 * The callback `fn(err)` is invoked when the transfer is complete183 * or when an error occurs. Be sure to check `res.sentHeader`184 * if you wish to attempt responding, as the header and some data185 * may have already been transferred.186 *187 * Options:188 *189 * - `maxAge` defaulting to 0190 * - `root` root directory for relative filenames191 *192 * @param {String} path193 * @param {Object|Function} options or fn194 * @param {Function} fn195 * @api public196 */197198res.sendfile = function(path, options, fn){199 var self = this200 , req = self.req201 , next = this.req.next202 , options = options || {};203204 // support function as second arg205 if ('function' == typeof options) {206 fn = options;207 options = {};208 }209210 // callback211 options.callback = function(err){212 if (err) {refactoringTj Holowaychukbefore adoptionf68ba2e
lines 213–216why, one step back213 // cast ENOENT214 if ('ENOENT' == err.code) err = 404;215216 // coerce numeric error to an ErrormergedTj Holowaychukbefore adoption547d18c
lines 217–218why, one step back217 // TODO: remove218 // TODO: remove docs for headerSent?using connects error code utilTj Holowaychukbefore adoptiona95a0ab
lines 219–220why, one step back219 if ('number' == typeof err) err = utils.error(err);220qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
line 221why, one step back221 // ditch content-disposition to prevent funky responsesutilize res.headerSent from connectTj Holowaychukbefore adoption40f8202
line 222why, one step back222 if (!self.headerSent) self.removeHeader('Content-Disposition');qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
line 223why, one step back223refactoringTj Holowaychukbefore adoptionf68ba2e
lines 224–225why, one step back224 // woot! callback available225 if (fn) return fn(err);Added forbidden testsTj Holowaychukbefore adoption2f76226
line 226why, one step back226qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
line 227why, one step back227 // lost in limbo if there's no callbackrefactoringTj Holowaychukbefore adoptionf68ba2e
line 228why, one step back228 if (self.headerSent) return;qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 229–246why, one step back229230 return req.next(err);231 }232233 fn && fn();234 };235236 // transfer237 options.path = encodeURIComponent(path);238 send(this.req, this, next, options);239};240241/**242 * Transfer the file at the given `path` as an attachment.243 *244 * Optionally providing an alternate attachment `filename`,245 * and optional callback `fn(err)`. The callback is invoked246 * when the data transfer is complete, or when an error hasmergedTj Holowaychukbefore adoption547d18c
line 247why, one step back247 * ocurred. Be sure to check `res.headerSent` if you plan to respond.qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 248–286why, one step back248 *249 * @param {String} path250 * @param {String|Function} filename or fn251 * @param {Function} fn252 * @api public253 */254255res.download = function(path, filename, fn){256 // support function as second arg257 if ('function' == typeof filename) {258 fn = filename;259 filename = null;260 }261262 return this.attachment(filename || path).sendfile(path, fn);263};264265/**266 * Set _Content-Type_ response header passed through `mime.lookup()`.267 *268 * Examples:269 *270 * var filename = 'path/to/image.png';271 * res.contentType(filename);272 * // res.headers['Content-Type'] is now "image/png"273 *274 * res.contentType('.html');275 * res.contentType('html');276 * res.contentType('json');277 * res.contentType('png');278 * res.type('png');279 *280 * @param {String} type281 * @return {ServerResponse} for chaining282 * @api public283 */284285res.contentType =286res.type = function(type){utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 287why, one step back287 return this.set('Content-Type', mime.lookup(type));Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25
lines 288–302why, one step back288};289290/**291 * Respond to the Acceptable formats using an `obj`292 * of mime-type callbacks.293 *294 * This method uses `req.accepted`, an array of295 * acceptable types ordered by their quality values.296 * When "Accept" is not present the _first_ callback297 * is invoked, otherwise the first match is used. When298 * no match is performed the server responds with299 * 406 "Not Acceptable".300 *301 * Examples:302 *renamed `res.respondTo()` to `res.format()`TJ Holowaychukbefore adoptionffcaa04
line 303why, one step back303 * res.format({Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25
lines 304–321why, one step back304 * 'text/plain': function(){305 * res.type('text').send('hey');306 * },307 * 308 * 'text/html': function(){309 * res.send('<p>hey</p>');310 * },311 * 312 * 'appliation/json': function(){313 * res.send({ message: 'hey' });314 * }315 * });316 *317 * @param {Object} obj318 * @return {ServerResponse} for chaining319 * @api public320 */321renamed `res.respondTo()` to `res.format()`TJ Holowaychukbefore adoptionffcaa04
line 322why, one step back322res.format = function(obj){Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25
lines 323–342why, one step back323 var keys = Object.keys(obj)324 , req = this.req325 , next = req.next326 , accepted = req.accepted327 , type328 , key;329330 out:331 for (var i = 0, len = accepted.length; i < len; ++i) {332 for (var j = 0, jlen = keys.length; j < jlen; ++j) {333 if (accept(keys[j].split('/'), accepted[i])) {334 key = keys[j];335 break out;336 }337 }338 }339340 if (!accepted.length) key = keys.shift();341342 if (key) {Added: `res.respondTo()` defaults the content-typeTJ Holowaychukbefore adoptionbdfa6d1
lines 343–344why, one step back343 this.set('Content-Type', key);344 obj[key](req, this, next);Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25
lines 345–352why, one step back345 } else {346 var err = new Error('Not Acceptable');347 err.status = 406;348 err.types = keys;349 next(err);350 }351352 return this;qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 353–363why, one step back353};354355/**356 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.357 *358 * @param {String} filename359 * @return {ServerResponse}360 * @api public361 */362363res.attachment = function(filename){misc refactoringTj Holowaychukbefore adoption4b0b55c
line 364why, one step back364 if (filename) this.type(filename);utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 365why, one step back365 this.set('Content-Disposition', filenameqs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 366–418why, one step back366 ? 'attachment; filename="' + basename(filename) + '"'367 : 'attachment');368 return this;369};370371/**372 * Set header `field` to `val`, or pass373 * an object of of header fields.374 *375 * Examples:376 *377 * res.set('Accept', 'application/json');378 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });379 *380 * @param {String|Object} field381 * @param {String} val382 * @return {ServerResponse} for chaining383 * @api public384 */385386res.set = function(field, val){387 if (2 == arguments.length) {388 this.setHeader(field, val);389 } else {390 for (var key in field) {391 this.setHeader(key, field[key]);392 }393 }394 return this;395};396397/**398 * Get value for header `field`.399 *400 * @param {String} field401 * @return {String}402 * @api public403 */404405res.get = function(field){406 return this.getHeader(field);407};408409/**410 * Clear cookie `name`.411 *412 * @param {String} name413 * @param {Object} options414 * @param {ServerResponse} for chaining415 * @api public416 */417418res.clearCookie = function(name, options){removed "root" settingTj Holowaychukbefore adoption87b991c
line 419why, one step back419 var opts = { expires: new Date(1), path: '/' };qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 420–425why, one step back420 return this.cookie(name, '', options421 ? utils.merge(opts, options)422 : opts);423};424425/**Added res.signedCookie() and tests. Closes #880Tj Holowaychukbefore adoption58eddd5
lines 426–443why, one step back426 * Set a signed cookie with the given `name` and `val`.427 * See `res.cookie()` for details.428 *429 * @param {String} name430 * @param {String|Object} val431 * @param {Object} options432 * @api public433 */434435res.signedCookie = function(name, val, options){436 var secret = this.req.secret;437 if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');438 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);439 val = utils.sign(val, secret);440 return this.cookie(name, val, options);441};442443/**qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 444–448why, one step back444 * Set cookie `name` to `val`, with the given `options`.445 *446 * Options:447 *448 * - `maxAge` max-age in milliseconds, converted to `expires`removed "root" settingTj Holowaychukbefore adoption87b991c
line 449why, one step back449 * - `path` defaults to "/"qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 450–459why, one step back450 *451 * Examples:452 *453 * // "Remember Me" for 15 minutes454 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });455 *456 * // save as above457 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })458 *459 * @param {String} nameAdded res.signedCookie() and tests. Closes #880Tj Holowaychukbefore adoption58eddd5
line 460why, one step back460 * @param {String|Object} valqs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 461–466why, one step back461 * @param {Options} options462 * @api public463 */464465res.cookie = function(name, val, options){466 options = options || {};Added JSON cookie support & tests. Closes #879Tj Holowaychukbefore adoption7ac857a
line 467why, one step back467 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
line 468why, one step back468 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption85ea5f6
line 469why, one step back469 if (null == options.path) options.path = '/';qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
line 470why, one step back470 var cookie = utils.serializeCookie(name, val, options);utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 471why, one step back471 this.set('Set-Cookie', cookie);qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 472–480why, one step back472 return this;473};474475/**476 * Redirect to the given `url` with optional response `status`477 * defaulting to 302.478 *479 * The given `url` can also be the name of a mapped url, for480 * example by default express supports "back" which redirectsremoved "root" settingTj Holowaychukbefore adoption87b991c
line 481why, one step back481 * to the _Referrer_ or _Referer_ headers or "/".qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 482–488why, one step back482 *483 * Examples:484 *485 * res.redirect('/foo/bar');486 * res.redirect('http://example.com');487 * res.redirect(301, 'http://example.com');488 *docsTj Holowaychukbefore adoption0f72ca8
lines 489–501why, one step back489 * Mounting:490 *491 * When an application is mounted, and `res.redirect()`492 * is given a path that does _not_ lead with "/". For 493 * example suppose a "blog" app is mounted at "/blog",494 * the following redirect would result in "/blog/login":495 *496 * res.redirect('login');497 *498 * While the leading slash would result in a redirect to "/login":499 *500 * res.redirect('/login');501 *qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 502–519why, one step back502 * @param {String} url503 * @param {Number} code504 * @api public505 */506507res.redirect = function(url){508 var app = this.app509 , req = this.req510 , head = 'HEAD' == req.method511 , status = 302512 , body;513514 // allow status / url515 if (2 == arguments.length) {516 status = url;517 url = arguments[1];518 }519Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 520why, one step back520 // setup redirect mapRemoved `res.header(field, value)`TJ Holowaychukbefore adoption76fd462
line 521why, one step back521 var map = { back: req.get('Referrer') || '/' };qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
line 522why, one step back522Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 523why, one step back523 // perform redirectRemoved `app.redirect()`Tj Holowaychukbefore adoption4329528
line 524why, one step back524 url = map[url] || url;qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
line 525why, one step back525Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 526why, one step back526 // relativeqs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
line 527why, one step back527 if (!~url.indexOf('://')) {more testsTj Holowaychukbefore adoptioncca5d7e
line 528why, one step back528 var path = app.path();use app.path() in res.redirect()Tj Holowaychukbefore adoptiona1e325a
line 529why, one step back529Added support for ./ in redirectsTj Holowaychukbefore adoption489265e
line 530why, one step back530 // relative to pathAdded support for .. in redirects as wellTj Holowaychukbefore adoption88f154f
lines 531–532why, one step back531 if (0 == url.indexOf('./') || 0 == url.indexOf('..')) {532 url = req.path + '/' + url;Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 533why, one step back533 // relative to mount-pointAdded support for ./ in redirectsTj Holowaychukbefore adoption489265e
line 534why, one step back534 } else if ('/' != url[0]) {Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
lines 535–536why, one step back535 url = path + '/' + url;536 }qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 537–538why, one step back537538 // AbsoluteRemoved `res.header(field, value)`TJ Holowaychukbefore adoption76fd462
line 539why, one step back539 var host = req.get('Host');Added "trust proxy" settingTJ Holowaychukbefore adoption4d87efc
line 540why, one step back540 url = req.protocol + '://' + host + url;qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 541–543why, one step back541 }542543 // Support text/{plain,html} by defaultrenamed `res.respondTo()` to `res.format()`TJ Holowaychukbefore adoptionffcaa04
line 544why, one step back544 this.format({refactored res.redirect() with respondTo()TJ Holowaychukbefore adoptiona47660b
lines 545–552why, one step back545 'text/plain': function(){546 body = statusCodes[status] + '. Redirecting to ' + url;547 },548549 'text/html': function(){550 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';551 }552 })qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 553–555why, one step back553554 // Respond555 this.statusCode = status;utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 556why, one step back556 this.set('Location', url);qs 0.3.2 to fix global var leakTj Holowaychukbefore adoptionf42ce5b
lines 557–629why, one step back557 this.end(head ? null : body);558};559560/**561 * Render `view` with the given `options` and optional callback `fn`.562 * When a callback function is given a response will _not_ be made563 * automatically, otherwise a response of _200_ and _text/html_ is given.564 *565 * Options:566 * 567 * - `status` Response status code (`res.statusCode`)568 * - `charset` Set the charset (`res.charset`)569 *570 * Reserved locals:571 *572 * - `cache` boolean hinting to the engine it should cache573 * - `filename` filename of the view being rendered574 *575 * @param {String} view576 * @param {Object|Function} options or callback function577 * @param {Function} fn578 * @api public579 */580581res.render = function(view, options, fn){582 var self = this583 , options = options || {}584 , req = this.req585 , app = req.app;586587 // support callback function as second arg588 if ('function' == typeof options) {589 fn = options, options = {};590 }591592 function render() {593 // merge res.locals594 options.locals = self.locals;595596 // default callback to respond597 fn = fn || function(err, str){598 if (err) return req.next(err);599 self.send(str);600 };601602 // render603 app.render(view, options, fn);604 }605606 // invoke view callbacks607 var callbacks = app.viewCallbacks608 , pending = callbacks.length609 , len = pending610 , done;611612 if (len) {613 for (var i = 0; i < len; ++i) {614 callbacks[i](req, self, function(err){615 if (done) return;616617 if (err) {618 req.next(err);619 done = true;620 return;621 }622623 --pending || render();624 });625 }626 } else {627 render();628 }629};