response.js
This file
Path
lib/response.js
576 lines · 13.0 KiB · JavaScript
Last changed by
Added X-Forwarded-Proto support to `res.redirect()`. Closes #927Tj Holowaychukbefore adoption5757f87
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–465why, one step back448 * @param {String} url449 * @param {Number} code450 * @api public451 */452453res.redirect = function(url){454 var app = this.app455 , req = this.req456 , head = 'HEAD' == req.method457 , status = 302458 , body;459460 // allow status / url461 if (2 == arguments.length) {462 status = url;463 url = arguments[1];464 }465Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 466why, one step back466 // setup redirect mapRemoved redirect "home"Tj Holowaychukbefore adoption1cda0a9
line 467why, one step back467 var map = { back: req.header('Referrer', '/') };Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 468why, one step back468Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 469why, one step back469 // perform redirectRemoved `app.redirect()`Tj Holowaychukbefore adoption4329528
line 470why, one step back470 url = map[url] || url;Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 471why, one step back471Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 472why, one step back472 // relativeAdded req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 473why, one step back473 if (!~url.indexOf('://')) {more testsTj Holowaychukbefore adoptioncca5d7e
line 474why, one step back474 var path = app.path();use app.path() in res.redirect()Tj Holowaychukbefore adoptiona1e325a
line 475why, one step back475Added support for ./ in redirectsTj Holowaychukbefore adoption489265e
line 476why, one step back476 // relative to pathAdded support for .. in redirects as wellTj Holowaychukbefore adoption88f154f
lines 477–478why, one step back477 if (0 == url.indexOf('./') || 0 == url.indexOf('..')) {478 url = req.path + '/' + url;Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
line 479why, one step back479 // relative to mount-pointAdded support for ./ in redirectsTj Holowaychukbefore adoption489265e
line 480why, one step back480 } else if ('/' != url[0]) {Added relative redirect support. Closes #920Tj Holowaychukbefore adoption43c8764
lines 481–482why, one step back481 url = path + '/' + url;482 }Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 483–484why, one step back483484 // Absolutetmp fixTj Holowaychukbefore adoption1faba13
line 485why, one step back485 var host = req.header('Host')Added X-Forwarded-Proto support to `res.redirect()`. Closes #927Tj Holowaychukbefore adoption5757f87
lines 486–487why, one step back486 , proto = req.header('X-Forwarded-Proto')487 , tls = 'https' == proto || req.secure;tmp fixTj Holowaychukbefore adoption1faba13
line 488why, one step back488Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 489–558why, one step back489 url = 'http' + (tls ? 's' : '') + '://' + host + url;490 }491492 // Support text/{plain,html} by default493 if (req.accepts('html')) {494 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';495 this.header('Content-Type', 'text/html');496 } else {497 body = statusCodes[status] + '. Redirecting to ' + url;498 this.header('Content-Type', 'text/plain');499 }500501 // Respond502 this.statusCode = status;503 this.header('Location', url);504 this.end(head ? null : body);505};506507/**508 * Render `view` with the given `options` and optional callback `fn`.509 * When a callback function is given a response will _not_ be made510 * automatically, otherwise a response of _200_ and _text/html_ is given.511 *512 * Options:513 * 514 * - `status` Response status code (`res.statusCode`)515 * - `charset` Set the charset (`res.charset`)516 *517 * Reserved locals:518 *519 * - `cache` boolean hinting to the engine it should cache520 * - `filename` filename of the view being rendered521 *522 * @param {String} view523 * @param {Object|Function} options or callback function524 * @param {Function} fn525 * @api public526 */527528res.render = function(view, options, fn){529 var self = this530 , options = options || {}531 , req = this.req532 , app = req.app;533534 // support callback function as second arg535 if ('function' == typeof options) {536 fn = options, options = {};537 }538539 function render() {540 // merge res.locals541 options.locals = self.locals;542543 // default callback to respond544 fn = fn || function(err, str){545 if (err) return req.next(err);546 self.send(str);547 };548549 // render550 app.render(view, options, fn);551 }552553 // invoke view callbacks554 var callbacks = app.viewCallbacks555 , pending = callbacks.length556 , len = pending557 , done;558refactored res.render()Tj Holowaychukbefore adoptionb433550
lines 559–562why, one step back559 if (len) {560 for (var i = 0; i < len; ++i) {561 callbacks[i](req, self, function(err){562 if (done) return;Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
line 563why, one step back563refactored res.render()Tj Holowaychukbefore adoptionb433550
lines 564–574why, one step back564 if (err) {565 req.next(err);566 done = true;567 return;568 }569570 --pending || render();571 });572 }573 } else {574 render();Added req.fresh and req.staleTj Holowaychukbefore adoption0e4e050
lines 575–576why, one step back575 }576};