response.js
This file
Path
lib/response.js
616 lines · 14.0 KiB · JavaScript
Last changed by
docsTj Holowaychukbefore adoption0f72ca8
History of this fileTake it
The walk stopped after 200 commits: lines older than 0e4e050 point at it.
Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
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 req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
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 req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 65–208why, 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':94 this.header('Content-Type') || this.contentType('.txt');95 this.statusCode = body;96 body = http.STATUS_CODES[body];97 break;98 // string defaulting to html99 case 'string':100 if (!this.header('Content-Type')) {101 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)) {110 this.header('Content-Type') || this.contentType('.bin');111 } else {112 return this.json(body);113 }114 break;115 }116117 // populate Content-Length118 if (undefined !== body && !this.header('Content-Length')) {119 this.header('Content-Length', Buffer.isBuffer(body)120 ? 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 }158159 var body = JSON.stringify(obj)160 , callback = this.req.query.callback161 , jsonp = this.app.enabled('jsonp callback');162163 this.charset = this.charset || 'utf-8';164 this.header('Content-Type', 'application/json');165166 if (callback && jsonp) {167 this.header('Content-Type', 'text/javascript');168 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';169 }170171 return this.send(body);172};173174/**175 * Transfer the file at the given `path`.176 * 177 * Automatically sets the _Content-Type_ response header field.178 * The callback `fn(err)` is invoked when the transfer is complete179 * or when an error occurs. Be sure to check `res.sentHeader`180 * if you wish to attempt responding, as the header and some data181 * may have already been transferred.182 *183 * Options:184 *185 * - `maxAge` defaulting to 0186 * - `root` root directory for relative filenames187 *188 * @param {String} path189 * @param {Object|Function} options or fn190 * @param {Function} fn191 * @api public192 */193194res.sendfile = function(path, options, fn){195 var self = this196 , req = self.req197 , next = this.req.next198 , options = options || {};199200 // support function as second arg201 if ('function' == typeof options) {202 fn = options;203 options = {};204 }205206 // callback207 options.callback = function(err){208 if (err) {refactoringTj Holowaychukbefore adoptionf68ba2e
lines 209–212why, one step back209 // cast ENOENT210 if ('ENOENT' == err.code) err = 404;211212 // coerce numeric error to an ErrormergedTj Holowaychukbefore adoption547d18c
lines 213–214why, one step back213 // TODO: remove214 // TODO: remove docs for headerSent?using connects error code utilTj Holowaychukbefore adoptiona95a0ab
lines 215–216why, one step back215 if ('number' == typeof err) err = utils.error(err);216Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 217why, one step back217 // ditch content-disposition to prevent funky responsesutilize res.headerSent from connectTj Holowaychukbefore adoption40f8202
line 218why, one step back218 if (!self.headerSent) self.removeHeader('Content-Disposition');Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 219why, one step back219refactoringTj Holowaychukbefore adoptionf68ba2e
lines 220–221why, one step back220 // woot! callback available221 if (fn) return fn(err);Added forbidden testsTj Holowaychukbefore adoption2f76226
line 222why, one step back222Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 223why, one step back223 // lost in limbo if there's no callbackrefactoringTj Holowaychukbefore adoptionf68ba2e
line 224why, one step back224 if (self.headerSent) return;Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 225–242why, one step back225226 return req.next(err);227 }228229 fn && fn();230 };231232 // transfer233 options.path = encodeURIComponent(path);234 send(this.req, this, next, options);235};236237/**238 * Transfer the file at the given `path` as an attachment.239 *240 * Optionally providing an alternate attachment `filename`,241 * and optional callback `fn(err)`. The callback is invoked242 * when the data transfer is complete, or when an error hasmergedTj Holowaychukbefore adoption547d18c
line 243why, one step back243 * ocurred. Be sure to check `res.headerSent` if you plan to respond.Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 244–294why, one step back244 *245 * @param {String} path246 * @param {String|Function} filename or fn247 * @param {Function} fn248 * @api public249 */250251res.download = function(path, filename, fn){252 // support function as second arg253 if ('function' == typeof filename) {254 fn = filename;255 filename = null;256 }257258 return this.attachment(filename || path).sendfile(path, fn);259};260261/**262 * Set _Content-Type_ response header passed through `mime.lookup()`.263 *264 * Examples:265 *266 * var filename = 'path/to/image.png';267 * res.contentType(filename);268 * // res.headers['Content-Type'] is now "image/png"269 *270 * res.contentType('.html');271 * res.contentType('html');272 * res.contentType('json');273 * res.contentType('png');274 * res.type('png');275 *276 * @param {String} type277 * @return {ServerResponse} for chaining278 * @api public279 */280281res.contentType =282res.type = function(type){283 return this.header('Content-Type', mime.lookup(type));284};285286/**287 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.288 *289 * @param {String} filename290 * @return {ServerResponse}291 * @api public292 */293294res.attachment = function(filename){misc refactoringTj Holowaychukbefore adoption4b0b55c
line 295why, one step back295 if (filename) this.type(filename);Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 296–364why, one step back296 this.header('Content-Disposition', filename297 ? 'attachment; filename="' + basename(filename) + '"'298 : 'attachment');299 return this;300};301302/**303 * Set header `field` to `val`, or pass304 * an object of of header fields.305 *306 * Examples:307 *308 * res.set('Accept', 'application/json');309 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });310 *311 * @param {String|Object} field312 * @param {String} val313 * @return {ServerResponse} for chaining314 * @api public315 */316317res.set = function(field, val){318 if (2 == arguments.length) {319 this.setHeader(field, val);320 } else {321 for (var key in field) {322 this.setHeader(key, field[key]);323 }324 }325 return this;326};327328/**329 * Get value for header `field`.330 *331 * @param {String} field332 * @return {String}333 * @api public334 */335336res.get = function(field){337 return this.getHeader(field);338};339340/**341 * Set or get response header `field` with optional `val`.342 *343 * @param {String} name344 * @param {String} val345 * @return {ServerResponse} for chaining346 * @api public347 */348349res.header = function(field, val){350 if (1 == arguments.length) return this.getHeader(field);351 this.setHeader(field, val);352 return this;353};354355/**356 * Clear cookie `name`.357 *358 * @param {String} name359 * @param {Object} options360 * @param {ServerResponse} for chaining361 * @api public362 */363364res.clearCookie = function(name, options){removed "root" settingTj Holowaychukbefore adoption87b991c
line 365why, one step back365 var opts = { expires: new Date(1), path: '/' };Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 366why, one step back366 return this.cookie(name, '', optionsFixed res.clearCookie(), default path to "root" settingTj Holowaychukbefore adoption0f2f3d4
line 367why, one step back367 ? utils.merge(opts, options)Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 368–371why, one step back368 : opts);369};370371/**Added res.signedCookie() and tests. Closes #880Tj Holowaychukbefore adoption58eddd5
lines 372–389why, one step back372 * Set a signed cookie with the given `name` and `val`.373 * See `res.cookie()` for details.374 *375 * @param {String} name376 * @param {String|Object} val377 * @param {Object} options378 * @api public379 */380381res.signedCookie = function(name, val, options){382 var secret = this.req.secret;383 if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');384 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);385 val = utils.sign(val, secret);386 return this.cookie(name, val, options);387};388389/**Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 390–394why, one step back390 * Set cookie `name` to `val`, with the given `options`.391 *392 * Options:393 *394 * - `maxAge` max-age in milliseconds, converted to `expires`removed "root" settingTj Holowaychukbefore adoption87b991c
line 395why, one step back395 * - `path` defaults to "/"Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 396–405why, one step back396 *397 * Examples:398 *399 * // "Remember Me" for 15 minutes400 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });401 *402 * // save as above403 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })404 *405 * @param {String} nameAdded res.signedCookie() and tests. Closes #880Tj Holowaychukbefore adoption58eddd5
line 406why, one step back406 * @param {String|Object} valAdded req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 407–412why, one step back407 * @param {Options} options408 * @api public409 */410411res.cookie = function(name, val, options){412 options = options || {};Added JSON cookie support & tests. Closes #879Tj Holowaychukbefore adoption7ac857a
line 413why, one step back413 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 414why, one step back414 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);removed "root" settingTj Holowaychukbefore adoption87b991c
line 415why, one step back415 if (undefined === options.path) options.path = '/';Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 416–426why, one step back416 var cookie = utils.serializeCookie(name, val, options);417 this.header('Set-Cookie', cookie);418 return this;419};420421/**422 * Redirect to the given `url` with optional response `status`423 * defaulting to 302.424 *425 * The given `url` can also be the name of a mapped url, for426 * example by default express supports "back" which redirectsremoved "root" settingTj Holowaychukbefore adoption87b991c
line 427why, one step back427 * to the _Referrer_ or _Referer_ headers or "/".Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 428–434why, one step back428 *429 * Examples:430 *431 * res.redirect('/foo/bar');432 * res.redirect('http://example.com');433 * res.redirect(301, 'http://example.com');434 *docsTj Holowaychukbefore adoption0f72ca8
lines 435–447why, one step back435 * Mounting:436 *437 * When an application is mounted, and `res.redirect()`438 * is given a path that does _not_ lead with "/". For 439 * example suppose a "blog" app is mounted at "/blog",440 * the following redirect would result in "/blog/login":441 *442 * res.redirect('login');443 *444 * While the leading slash would result in a redirect to "/login":445 *446 * res.redirect('/login');447 *Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 448–461why, one step back448 * Redirect Mapping:449 * 450 * To extend the redirect mapping capabilities that Express provides,451 * we may use the `app.redirect()` method:452 * 453 * app.redirect('google', 'http://google.com');454 * 455 * Now in a route we may call:456 *457 * res.redirect('google');458 *459 * We may also map dynamic redirects:460 *461 * app.redirect('comments', function(req, res){miscTj Holowaychukbefore adoption41786bc
line 462why, one step back462 * return '/post/' + req.params.id + '/comments';Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 463–484why, one step back463 * });464 *465 * So now we may do the following, and the redirect will dynamically adjust to466 * the context of the request. If we called this route with _GET /post/12_ our467 * redirect _Location_ would be _/post/12/comments_.468 *469 * app.get('/post/:id', function(req, res){470 * res.redirect('comments');471 * });472 *473 * Unless an absolute `url` is given, the app's mount-point474 * will be respected. For example if we redirect to `/posts`,475 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.476 *477 * @param {String} url478 * @param {Number} code479 * @api public480 */481482res.redirect = function(url){483 var app = this.app484 , req = this.reqremoved uses of "root"Tj Holowaychukbefore adoption1d0a56b
line 485why, one step back485 , root = '/'Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 486–495why, one step back486 , head = 'HEAD' == req.method487 , status = 302488 , body;489490 // allow status / url491 if (2 == arguments.length) {492 status = url;493 url = arguments[1];494 }495Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 496why, one step back496 // setup redirect mapAdded req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 497why, one step back497 var map = {tweak res.redirect() mount route logicTj Holowaychukbefore adoption43d9f6e
lines 498–499why, one step back498 back: req.header('Referrer', root)499 , home: rootAdded req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 500–501why, one step back500 };501Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 502why, one step back502 // support custom redirect mapAdded req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 503–504why, one step back503 map.__proto__ = app.redirects;504Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 505why, one step back505 // attempt mapped redirectAdded req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 506–509why, one step back506 var mapped = 'function' == typeof map[url]507 ? map[url](req, this)508 : map[url];509Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 510why, one step back510 // perform redirectAdded req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 511–512why, one step back511 url = mapped || url;512Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 513why, one step back513 // relativeAdded req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 514why, one step back514 if (!~url.indexOf('://')) {more testsTj Holowaychukbefore adoptioncca5d7e
line 515why, one step back515 var path = app.path();use app.path() in res.redirect()Tj Holowaychukbefore adoptiona1e325a
line 516why, one step back516Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
lines 517–523why, one step back517 // relative to host518 if ('/' == url[0]) {519520 // relative to mount-point521 } else if (1 != url.indexOf(path)) {522 url = path + '/' + url;523 }Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 524–525why, one step back524525 // Absolutetmp fixTj Holowaychukbefore adoption1faba13
lines 526–528why, one step back526 var host = req.header('Host')527 , tls = false // TODO: req.secure;528Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 529–598why, one step back529 url = 'http' + (tls ? 's' : '') + '://' + host + url;530 }531532 // Support text/{plain,html} by default533 if (req.accepts('html')) {534 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';535 this.header('Content-Type', 'text/html');536 } else {537 body = statusCodes[status] + '. Redirecting to ' + url;538 this.header('Content-Type', 'text/plain');539 }540541 // Respond542 this.statusCode = status;543 this.header('Location', url);544 this.end(head ? null : body);545};546547/**548 * Render `view` with the given `options` and optional callback `fn`.549 * When a callback function is given a response will _not_ be made550 * automatically, otherwise a response of _200_ and _text/html_ is given.551 *552 * Options:553 * 554 * - `status` Response status code (`res.statusCode`)555 * - `charset` Set the charset (`res.charset`)556 *557 * Reserved locals:558 *559 * - `cache` boolean hinting to the engine it should cache560 * - `filename` filename of the view being rendered561 *562 * @param {String} view563 * @param {Object|Function} options or callback function564 * @param {Function} fn565 * @api public566 */567568res.render = function(view, options, fn){569 var self = this570 , options = options || {}571 , req = this.req572 , app = req.app;573574 // support callback function as second arg575 if ('function' == typeof options) {576 fn = options, options = {};577 }578579 function render() {580 // merge res.locals581 options.locals = self.locals;582583 // default callback to respond584 fn = fn || function(err, str){585 if (err) return req.next(err);586 self.send(str);587 };588589 // render590 app.render(view, options, fn);591 }592593 // invoke view callbacks594 var callbacks = app.viewCallbacks595 , pending = callbacks.length596 , len = pending597 , done;598refactored res.render()Tj Holowaychukbefore adoptionb433550
lines 599–602why, one step back599 if (len) {600 for (var i = 0; i < len; ++i) {601 callbacks[i](req, self, function(err){602 if (done) return;Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 603why, one step back603refactored res.render()Tj Holowaychukbefore adoptionb433550
lines 604–614why, one step back604 if (err) {605 req.next(err);606 done = true;607 return;608 }609610 --pending || render();611 });612 }613 } else {614 render();Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 615–616why, one step back615 }616};