response.js
This file
Path
lib/response.js
561 lines · 12.6 KiB · JavaScript
Last changed by
Removed `res.header(field, value)`TJ Holowaychukbefore adoption76fd462
History of this fileTake it
The walk stopped after 200 commits: lines older than f98c112 point at it.
Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 1–21why, 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.utils17 , statusCodes = http.STATUS_CODES18 , send = connect.static.send19 , mime = require('mime')20 , basename = path.basename21 , join = path.join;no longer manipulate the req/res protos directlyTj Holowaychukbefore adoptiond249868
lines 22–29why, one step back2223/**24 * Response prototype.25 */2627var res = module.exports = {28 __proto__: http.ServerResponse.prototype29};Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 30–31why, one step back3031/**miscTj Holowaychukbefore adoption61ce6c5
lines 32–44why, one step back32 * Set status `code`.33 *34 * @param {Number} code35 * @return {ServerResponse}36 * @api public37 */3839res.status = function(code){40 this.statusCode = code;41 return this;42};4344/**Added res.cache() methodTj Holowaychukbefore adoptione21a79d
line 45why, one step back45 * Set Cache-Control to the given `type` and `options`.Added res.cache(str)Tj Holowaychukbefore adoptioncaec590
line 46why, one step back46 *docsTj Holowaychukbefore adoptionbf87d62
lines 47–50why, one step back47 * Options:48 *49 * - `maxAge` in milliseconds50 *Added res.cache() methodTj Holowaychukbefore adoptione21a79d
lines 51–52why, one step back51 * @param {String} type52 * @param {Object} optionsAdded res.cache(str)Tj Holowaychukbefore adoptioncaec590
lines 53–56why, one step back53 * @return {ServerResponse}54 * @api public55 */56Added res.cache() methodTj Holowaychukbefore adoptione21a79d
lines 57–61why, one step back57res.cache = function(type, options){58 var val = type;59 options = options || {};60 if (options.maxAge) val += ', max-age=' + (options.maxAge / 1000); 61 return this.set('Cache-Control', val);Added res.cache(str)Tj Holowaychukbefore adoptioncaec590
lines 62–64why, one step back62};6364/**Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 65–93why, one step back65 * Send a response.66 *67 * Examples:68 *69 * res.send(new Buffer('wahoo'));70 * res.send({ some: 'json' });71 * res.send('<p>some html</p>');72 * res.send(404, 'Sorry, cant find that');73 * res.send(404);74 *75 * @param {Mixed} body or status76 * @param {Mixed} body77 * @return {ServerResponse}78 * @api public79 */8081res.send = function(body){82 var req = this.req83 , head = 'HEAD' == req.method;8485 // allow status / body86 if (2 == arguments.length) {87 this.statusCode = body;88 body = arguments[1];89 }9091 switch (typeof body) {92 // response status93 case 'number':utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 94why, one step back94 this.get('Content-Type') || this.contentType('.txt');Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 95–99why, one step back95 this.statusCode = body;96 body = http.STATUS_CODES[body];97 break;98 // string defaulting to html99 case 'string':utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 100why, one step back100 if (!this.get('Content-Type')) {Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 101–109why, one step back101 this.charset = this.charset || 'utf-8';102 this.contentType('.html');103 }104 break;105 case 'boolean':106 case 'object':107 if (null == body) {108 body = '';109 } else if (Buffer.isBuffer(body)) {utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 110why, one step back110 this.get('Content-Type') || this.contentType('.bin');Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 111–117why, one step back111 } else {112 return this.json(body);113 }114 break;115 }116117 // populate Content-Lengthutilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
lines 118–119why, one step back118 if (undefined !== body && !this.get('Content-Length')) {119 this.set('Content-Length', Buffer.isBuffer(body)Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 120–158why, one step back120 ? body.length121 : Buffer.byteLength(body));122 }123124 // strip irrelevant headers125 if (204 == this.statusCode || 304 == this.statusCode) {126 this.removeHeader('Content-Type');127 this.removeHeader('Content-Length');128 body = '';129 }130131 // respond132 this.end(head ? null : body);133 return this;134};135136/**137 * Send JSON response.138 *139 * Examples:140 *141 * res.json(null);142 * res.json({ user: 'tj' });143 * res.json(500, 'oh noes!');144 * res.json(404, 'I dont have that');145 *146 * @param {Mixed} obj or status147 * @param {Mixed} obj148 * @return {ServerResponse}149 * @api public150 */151152res.json = function(obj){153 // allow status / body154 if (2 == arguments.length) {155 this.statusCode = obj;156 obj = arguments[1];157 }158Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa
lines 159–164why, one step back159 var settings = this.app.settings160 , jsonp = settings['jsonp callback']161 , replacer = settings['json replacer']162 , spaces = settings['json spaces']163 , body = JSON.stringify(obj, replacer, spaces)164 , callback = this.req.query.callback;Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 165–166why, one step back165166 this.charset = this.charset || 'utf-8';utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 167why, one step back167 this.set('Content-Type', 'application/json');Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 168–169why, one step back168169 if (callback && jsonp) {utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 170why, one step back170 this.set('Content-Type', 'text/javascript');Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 171–211why, one step back171 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';172 }173174 return this.send(body);175};176177/**178 * Transfer the file at the given `path`.179 * 180 * Automatically sets the _Content-Type_ response header field.181 * The callback `fn(err)` is invoked when the transfer is complete182 * or when an error occurs. Be sure to check `res.sentHeader`183 * if you wish to attempt responding, as the header and some data184 * may have already been transferred.185 *186 * Options:187 *188 * - `maxAge` defaulting to 0189 * - `root` root directory for relative filenames190 *191 * @param {String} path192 * @param {Object|Function} options or fn193 * @param {Function} fn194 * @api public195 */196197res.sendfile = function(path, options, fn){198 var self = this199 , req = self.req200 , next = this.req.next201 , options = options || {};202203 // support function as second arg204 if ('function' == typeof options) {205 fn = options;206 options = {};207 }208209 // callback210 options.callback = function(err){211 if (err) {refactoringTj Holowaychukbefore adoptionf68ba2e
lines 212–215why, one step back212 // cast ENOENT213 if ('ENOENT' == err.code) err = 404;214215 // coerce numeric error to an ErrormergedTj Holowaychukbefore adoption547d18c
lines 216–217why, one step back216 // TODO: remove217 // TODO: remove docs for headerSent?using connects error code utilTj Holowaychukbefore adoptiona95a0ab
lines 218–219why, one step back218 if ('number' == typeof err) err = utils.error(err);219Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
line 220why, one step back220 // ditch content-disposition to prevent funky responsesutilize res.headerSent from connectTj Holowaychukbefore adoption40f8202
line 221why, one step back221 if (!self.headerSent) self.removeHeader('Content-Disposition');Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
line 222why, one step back222refactoringTj Holowaychukbefore adoptionf68ba2e
lines 223–224why, one step back223 // woot! callback available224 if (fn) return fn(err);Added forbidden testsTj Holowaychukbefore adoption2f76226
line 225why, one step back225Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
line 226why, one step back226 // lost in limbo if there's no callbackrefactoringTj Holowaychukbefore adoptionf68ba2e
line 227why, one step back227 if (self.headerSent) return;Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 228–245why, one step back228229 return req.next(err);230 }231232 fn && fn();233 };234235 // transfer236 options.path = encodeURIComponent(path);237 send(this.req, this, next, options);238};239240/**241 * Transfer the file at the given `path` as an attachment.242 *243 * Optionally providing an alternate attachment `filename`,244 * and optional callback `fn(err)`. The callback is invoked245 * when the data transfer is complete, or when an error hasmergedTj Holowaychukbefore adoption547d18c
line 246why, one step back246 * ocurred. Be sure to check `res.headerSent` if you plan to respond.Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 247–285why, one step back247 *248 * @param {String} path249 * @param {String|Function} filename or fn250 * @param {Function} fn251 * @api public252 */253254res.download = function(path, filename, fn){255 // support function as second arg256 if ('function' == typeof filename) {257 fn = filename;258 filename = null;259 }260261 return this.attachment(filename || path).sendfile(path, fn);262};263264/**265 * Set _Content-Type_ response header passed through `mime.lookup()`.266 *267 * Examples:268 *269 * var filename = 'path/to/image.png';270 * res.contentType(filename);271 * // res.headers['Content-Type'] is now "image/png"272 *273 * res.contentType('.html');274 * res.contentType('html');275 * res.contentType('json');276 * res.contentType('png');277 * res.type('png');278 *279 * @param {String} type280 * @return {ServerResponse} for chaining281 * @api public282 */283284res.contentType =285res.type = function(type){utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 286why, one step back286 return this.set('Content-Type', mime.lookup(type));Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 287–297why, one step back287};288289/**290 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.291 *292 * @param {String} filename293 * @return {ServerResponse}294 * @api public295 */296297res.attachment = function(filename){misc refactoringTj Holowaychukbefore adoption4b0b55c
line 298why, one step back298 if (filename) this.type(filename);utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 299why, one step back299 this.set('Content-Disposition', filenameAdded app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 300–352why, one step back300 ? 'attachment; filename="' + basename(filename) + '"'301 : 'attachment');302 return this;303};304305/**306 * Set header `field` to `val`, or pass307 * an object of of header fields.308 *309 * Examples:310 *311 * res.set('Accept', 'application/json');312 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });313 *314 * @param {String|Object} field315 * @param {String} val316 * @return {ServerResponse} for chaining317 * @api public318 */319320res.set = function(field, val){321 if (2 == arguments.length) {322 this.setHeader(field, val);323 } else {324 for (var key in field) {325 this.setHeader(key, field[key]);326 }327 }328 return this;329};330331/**332 * Get value for header `field`.333 *334 * @param {String} field335 * @return {String}336 * @api public337 */338339res.get = function(field){340 return this.getHeader(field);341};342343/**344 * Clear cookie `name`.345 *346 * @param {String} name347 * @param {Object} options348 * @param {ServerResponse} for chaining349 * @api public350 */351352res.clearCookie = function(name, options){removed "root" settingTj Holowaychukbefore adoption87b991c
line 353why, one step back353 var opts = { expires: new Date(1), path: '/' };Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 354–359why, one step back354 return this.cookie(name, '', options355 ? utils.merge(opts, options)356 : opts);357};358359/**Added res.signedCookie() and tests. Closes #880Tj Holowaychukbefore adoption58eddd5
lines 360–377why, one step back360 * Set a signed cookie with the given `name` and `val`.361 * See `res.cookie()` for details.362 *363 * @param {String} name364 * @param {String|Object} val365 * @param {Object} options366 * @api public367 */368369res.signedCookie = function(name, val, options){370 var secret = this.req.secret;371 if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');372 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);373 val = utils.sign(val, secret);374 return this.cookie(name, val, options);375};376377/**Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 378–382why, one step back378 * Set cookie `name` to `val`, with the given `options`.379 *380 * Options:381 *382 * - `maxAge` max-age in milliseconds, converted to `expires`removed "root" settingTj Holowaychukbefore adoption87b991c
line 383why, one step back383 * - `path` defaults to "/"Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 384–393why, one step back384 *385 * Examples:386 *387 * // "Remember Me" for 15 minutes388 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });389 *390 * // save as above391 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })392 *393 * @param {String} nameAdded res.signedCookie() and tests. Closes #880Tj Holowaychukbefore adoption58eddd5
line 394why, one step back394 * @param {String|Object} valAdded app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 395–400why, one step back395 * @param {Options} options396 * @api public397 */398399res.cookie = function(name, val, options){400 options = options || {};Added JSON cookie support & tests. Closes #879Tj Holowaychukbefore adoption7ac857a
line 401why, one step back401 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
line 402why, one step back402 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption85ea5f6
line 403why, one step back403 if (null == options.path) options.path = '/';Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
line 404why, one step back404 var cookie = utils.serializeCookie(name, val, options);utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 405why, one step back405 this.set('Set-Cookie', cookie);Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 406–414why, one step back406 return this;407};408409/**410 * Redirect to the given `url` with optional response `status`411 * defaulting to 302.412 *413 * The given `url` can also be the name of a mapped url, for414 * example by default express supports "back" which redirectsremoved "root" settingTj Holowaychukbefore adoption87b991c
line 415why, one step back415 * to the _Referrer_ or _Referer_ headers or "/".Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 416–422why, one step back416 *417 * Examples:418 *419 * res.redirect('/foo/bar');420 * res.redirect('http://example.com');421 * res.redirect(301, 'http://example.com');422 *docsTj Holowaychukbefore adoption0f72ca8
lines 423–435why, one step back423 * Mounting:424 *425 * When an application is mounted, and `res.redirect()`426 * is given a path that does _not_ lead with "/". For 427 * example suppose a "blog" app is mounted at "/blog",428 * the following redirect would result in "/blog/login":429 *430 * res.redirect('login');431 *432 * While the leading slash would result in a redirect to "/login":433 *434 * res.redirect('/login');435 *Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 436–453why, one step back436 * @param {String} url437 * @param {Number} code438 * @api public439 */440441res.redirect = function(url){442 var app = this.app443 , req = this.req444 , head = 'HEAD' == req.method445 , status = 302446 , body;447448 // allow status / url449 if (2 == arguments.length) {450 status = url;451 url = arguments[1];452 }453Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 454why, one step back454 // setup redirect mapRemoved `res.header(field, value)`TJ Holowaychukbefore adoption76fd462
line 455why, one step back455 var map = { back: req.get('Referrer') || '/' };Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
line 456why, one step back456Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 457why, one step back457 // perform redirectRemoved `app.redirect()`Tj Holowaychukbefore adoption4329528
line 458why, one step back458 url = map[url] || url;Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
line 459why, one step back459Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 460why, one step back460 // relativeAdded app.render() local precedence testTj Holowaychukbefore adoptionf98c112
line 461why, one step back461 if (!~url.indexOf('://')) {more testsTj Holowaychukbefore adoptioncca5d7e
line 462why, one step back462 var path = app.path();use app.path() in res.redirect()Tj Holowaychukbefore adoptiona1e325a
line 463why, one step back463Added support for ./ in redirectsTj Holowaychukbefore adoption489265e
line 464why, one step back464 // relative to pathAdded support for .. in redirects as wellTj Holowaychukbefore adoption88f154f
lines 465–466why, one step back465 if (0 == url.indexOf('./') || 0 == url.indexOf('..')) {466 url = req.path + '/' + url;Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 467why, one step back467 // relative to mount-pointAdded support for ./ in redirectsTj Holowaychukbefore adoption489265e
line 468why, one step back468 } else if ('/' != url[0]) {Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
lines 469–470why, one step back469 url = path + '/' + url;470 }Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 471–472why, one step back471472 // AbsoluteRemoved `res.header(field, value)`TJ Holowaychukbefore adoption76fd462
line 473why, one step back473 var host = req.get('Host');Added "trust proxy" settingTJ Holowaychukbefore adoption4d87efc
line 474why, one step back474 url = req.protocol + '://' + host + url;Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 475–479why, one step back475 }476477 // Support text/{plain,html} by default478 if (req.accepts('html')) {479 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 480why, one step back480 this.set('Content-Type', 'text/html');Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 481–482why, one step back481 } else {482 body = statusCodes[status] + '. Redirecting to ' + url;utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 483why, one step back483 this.set('Content-Type', 'text/plain');Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 484–487why, one step back484 }485486 // Respond487 this.statusCode = status;utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018
line 488why, one step back488 this.set('Location', url);Added app.render() local precedence testTj Holowaychukbefore adoptionf98c112
lines 489–561why, one step back489 this.end(head ? null : body);490};491492/**493 * Render `view` with the given `options` and optional callback `fn`.494 * When a callback function is given a response will _not_ be made495 * automatically, otherwise a response of _200_ and _text/html_ is given.496 *497 * Options:498 * 499 * - `status` Response status code (`res.statusCode`)500 * - `charset` Set the charset (`res.charset`)501 *502 * Reserved locals:503 *504 * - `cache` boolean hinting to the engine it should cache505 * - `filename` filename of the view being rendered506 *507 * @param {String} view508 * @param {Object|Function} options or callback function509 * @param {Function} fn510 * @api public511 */512513res.render = function(view, options, fn){514 var self = this515 , options = options || {}516 , req = this.req517 , app = req.app;518519 // support callback function as second arg520 if ('function' == typeof options) {521 fn = options, options = {};522 }523524 function render() {525 // merge res.locals526 options.locals = self.locals;527528 // default callback to respond529 fn = fn || function(err, str){530 if (err) return req.next(err);531 self.send(str);532 };533534 // render535 app.render(view, options, fn);536 }537538 // invoke view callbacks539 var callbacks = app.viewCallbacks540 , pending = callbacks.length541 , len = pending542 , done;543544 if (len) {545 for (var i = 0; i < len; ++i) {546 callbacks[i](req, self, function(err){547 if (done) return;548549 if (err) {550 req.next(err);551 done = true;552 return;553 }554555 --pending || render();556 });557 }558 } else {559 render();560 }561};