Skip to content
Myr

response.js

This file

Path

lib/response.js

596 lines · 13.7 KiB · JavaScript

Last changed by

refactoringTj Holowaychukbefore adoptionf961022

History of this file

Take it

The walk stopped after 200 commits: lines older than e1da383 point at it.

new ViewTj Holowaychukbefore adoptione1da383

lines 1–21why, one step back
1
2/*!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 back
22
23/**24 * Response prototype.25 */2627var res = module.exports = {28 __proto__: http.ServerResponse.prototype29};

new ViewTj Holowaychukbefore adoptione1da383

lines 30–31why, one step back
30
31/**

miscTj Holowaychukbefore adoption61ce6c5

lines 32–44why, one step back
32 * 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 back
45 * Set Cache-Control to the given `type` and `options`.

Added res.cache(str)Tj Holowaychukbefore adoptioncaec590

line 46why, one step back
46 *

docsTj Holowaychukbefore adoptionbf87d62

lines 47–50why, one step back
47 * Options:
48 *49 * - `maxAge` in milliseconds50 *

Added res.cache() methodTj Holowaychukbefore adoptione21a79d

lines 51–52why, one step back
51 * @param {String} type
52 * @param {Object} options

Added res.cache(str)Tj Holowaychukbefore adoptioncaec590

lines 53–56why, one step back
53 * @return {ServerResponse}
54 * @api public55 */56

Added res.cache() methodTj Holowaychukbefore adoptione21a79d

lines 57–61why, one step back
57res.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 back
62};
6364/**

new ViewTj Holowaychukbefore adoptione1da383

lines 65–208why, one step back
65 * 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 back
209 // cast ENOENT
210 if ('ENOENT' == err.code) err = 404;211212 // coerce numeric error to an Error

using connects error code utilTj Holowaychukbefore adoptiona95a0ab

lines 213–214why, one step back
213 if ('number' == typeof err) err = utils.error(err);
214

new ViewTj Holowaychukbefore adoptione1da383

line 215why, one step back
215 // ditch content-disposition to prevent funky responses

utilize res.headerSent from connectTj Holowaychukbefore adoption40f8202

line 216why, one step back
216 if (!self.headerSent) self.removeHeader('Content-Disposition');

new ViewTj Holowaychukbefore adoptione1da383

line 217why, one step back
217

refactoringTj Holowaychukbefore adoptionf68ba2e

lines 218–219why, one step back
218 // woot! callback available
219 if (fn) return fn(err);

Added forbidden testsTj Holowaychukbefore adoption2f76226

line 220why, one step back
220

new ViewTj Holowaychukbefore adoptione1da383

line 221why, one step back
221 // lost in limbo if there's no callback

refactoringTj Holowaychukbefore adoptionf68ba2e

line 222why, one step back
222 if (self.headerSent) return;

new ViewTj Holowaychukbefore adoptione1da383

lines 223–292why, one step back
223
224 return req.next(err);225 }226227 fn && fn();228 };229230 // transfer231 options.path = encodeURIComponent(path);232 send(this.req, this, next, options);233};234235/**236 * Transfer the file at the given `path` as an attachment.237 *238 * Optionally providing an alternate attachment `filename`,239 * and optional callback `fn(err)`. The callback is invoked240 * when the data transfer is complete, or when an error has241 * ocurred. Be sure to check `res.sendHeader` if you plan to respond.242 *243 * @param {String} path244 * @param {String|Function} filename or fn245 * @param {Function} fn246 * @api public247 */248249res.download = function(path, filename, fn){250 // support function as second arg251 if ('function' == typeof filename) {252 fn = filename;253 filename = null;254 }255256 return this.attachment(filename || path).sendfile(path, fn);257};258259/**260 * Set _Content-Type_ response header passed through `mime.lookup()`.261 *262 * Examples:263 *264 * var filename = 'path/to/image.png';265 * res.contentType(filename);266 * // res.headers['Content-Type'] is now "image/png"267 *268 * res.contentType('.html');269 * res.contentType('html');270 * res.contentType('json');271 * res.contentType('png');272 * res.type('png');273 *274 * @param {String} type275 * @return {ServerResponse} for chaining276 * @api public277 */278279res.contentType =280res.type = function(type){281 return this.header('Content-Type', mime.lookup(type));282};283284/**285 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.286 *287 * @param {String} filename288 * @return {ServerResponse}289 * @api public290 */291292res.attachment = function(filename){

misc refactoringTj Holowaychukbefore adoption4b0b55c

line 293why, one step back
293 if (filename) this.type(filename);

new ViewTj Holowaychukbefore adoptione1da383

lines 294–362why, one step back
294 this.header('Content-Disposition', filename
295 ? 'attachment; filename="' + basename(filename) + '"'296 : 'attachment');297 return this;298};299300/**301 * Set header `field` to `val`, or pass302 * an object of of header fields.303 *304 * Examples:305 *306 * res.set('Accept', 'application/json');307 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });308 *309 * @param {String|Object} field310 * @param {String} val311 * @return {ServerResponse} for chaining312 * @api public313 */314315res.set = function(field, val){316 if (2 == arguments.length) {317 this.setHeader(field, val);318 } else {319 for (var key in field) {320 this.setHeader(key, field[key]);321 }322 }323 return this;324};325326/**327 * Get value for header `field`.328 *329 * @param {String} field330 * @return {String}331 * @api public332 */333334res.get = function(field){335 return this.getHeader(field);336};337338/**339 * Set or get response header `field` with optional `val`.340 *341 * @param {String} name342 * @param {String} val343 * @return {ServerResponse} for chaining344 * @api public345 */346347res.header = function(field, val){348 if (1 == arguments.length) return this.getHeader(field);349 this.setHeader(field, val);350 return this;351};352353/**354 * Clear cookie `name`.355 *356 * @param {String} name357 * @param {Object} options358 * @param {ServerResponse} for chaining359 * @api public360 */361362res.clearCookie = function(name, options){

Fixed res.clearCookie(), default path to "root" settingTj Holowaychukbefore adoption0f2f3d4

line 363why, one step back
363 var opts = { expires: new Date(1), path: this.app.get('root') };

new ViewTj Holowaychukbefore adoptione1da383

line 364why, one step back
364 return this.cookie(name, '', options

Fixed res.clearCookie(), default path to "root" settingTj Holowaychukbefore adoption0f2f3d4

line 365why, one step back
365 ? utils.merge(opts, options)

new ViewTj Holowaychukbefore adoptione1da383

lines 366–369why, one step back
366 : opts);
367};368369/**

Added res.signedCookie() and tests. Closes #880Tj Holowaychukbefore adoption58eddd5

lines 370–387why, one step back
370 * Set a signed cookie with the given `name` and `val`.
371 * See `res.cookie()` for details.372 *373 * @param {String} name374 * @param {String|Object} val375 * @param {Object} options376 * @api public377 */378379res.signedCookie = function(name, val, options){380 var secret = this.req.secret;381 if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');382 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);383 val = utils.sign(val, secret);384 return this.cookie(name, val, options);385};386387/**

new ViewTj Holowaychukbefore adoptione1da383

lines 388–392why, one step back
388 * Set cookie `name` to `val`, with the given `options`.
389 *390 * Options:391 *392 * - `maxAge` max-age in milliseconds, converted to `expires`

Added relative redirect testTj Holowaychukbefore adoption55ee0a0

line 393why, one step back
393 * - `path` defaults to the "root" setting which is typically "/"

new ViewTj Holowaychukbefore adoptione1da383

lines 394–403why, one step back
394 *
395 * Examples:396 *397 * // "Remember Me" for 15 minutes398 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });399 *400 * // save as above401 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })402 *403 * @param {String} name

Added res.signedCookie() and tests. Closes #880Tj Holowaychukbefore adoption58eddd5

line 404why, one step back
404 * @param {String|Object} val

new ViewTj Holowaychukbefore adoptione1da383

lines 405–410why, one step back
405 * @param {Options} options
406 * @api public407 */408409res.cookie = function(name, val, options){410 options = options || {};

Added JSON cookie support & tests. Closes #879Tj Holowaychukbefore adoption7ac857a

line 411why, one step back
411 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);

new ViewTj Holowaychukbefore adoptione1da383

line 412why, one step back
412 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);

Fixed res.cookie() path defaultTj Holowaychukbefore adoptionbee0496

line 413why, one step back
413 if (undefined === options.path) options.path = this.app.set('root');

new ViewTj Holowaychukbefore adoptione1da383

lines 414–425why, one step back
414 var cookie = utils.serializeCookie(name, val, options);
415 this.header('Set-Cookie', cookie);416 return this;417};418419/**420 * Redirect to the given `url` with optional response `status`421 * defaulting to 302.422 *423 * The given `url` can also be the name of a mapped url, for424 * example by default express supports "back" which redirects425 * to the _Referrer_ or _Referer_ headers or the application's

Added relative redirect testTj Holowaychukbefore adoption55ee0a0

lines 426–427why, one step back
426 * "root" setting. Express also supports "root" out of the box,
427 * which can be set via `app.set('root', '/blog');`.

new ViewTj Holowaychukbefore adoptione1da383

lines 428–471why, one step back
428 *
429 * Examples:430 *431 * res.redirect('/foo/bar');432 * res.redirect('http://example.com');433 * res.redirect(301, 'http://example.com');434 *435 * Redirect Mapping:436 * 437 * To extend the redirect mapping capabilities that Express provides,438 * we may use the `app.redirect()` method:439 * 440 * app.redirect('google', 'http://google.com');441 * 442 * Now in a route we may call:443 *444 * res.redirect('google');445 *446 * We may also map dynamic redirects:447 *448 * app.redirect('comments', function(req, res){449 * return '/post/' + req.params.id + '/comments';450 * });451 *452 * So now we may do the following, and the redirect will dynamically adjust to453 * the context of the request. If we called this route with _GET /post/12_ our454 * redirect _Location_ would be _/post/12/comments_.455 *456 * app.get('/post/:id', function(req, res){457 * res.redirect('comments');458 * });459 *460 * Unless an absolute `url` is given, the app's mount-point461 * will be respected. For example if we redirect to `/posts`,462 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.463 *464 * @param {String} url465 * @param {Number} code466 * @api public467 */468469res.redirect = function(url){470 var app = this.app471 , req = this.req

tweak res.redirect() mount route logicTj Holowaychukbefore adoption43d9f6e

line 472why, one step back
472 , root = app.get('root')

new ViewTj Holowaychukbefore adoptione1da383

lines 473–484why, one step back
473 , head = 'HEAD' == req.method
474 , status = 302475 , body;476477 // allow status / url478 if (2 == arguments.length) {479 status = url;480 url = arguments[1];481 }482483 // Setup redirect map484 var map = {

tweak res.redirect() mount route logicTj Holowaychukbefore adoption43d9f6e

lines 485–486why, one step back
485 back: req.header('Referrer', root)
486 , home: root

new ViewTj Holowaychukbefore adoptione1da383

lines 487–502why, one step back
487 };
488489 // Support custom redirect map490 map.__proto__ = app.redirects;491492 // Attempt mapped redirect493 var mapped = 'function' == typeof map[url]494 ? map[url](req, this)495 : map[url];496497 // Perform redirect498 url = mapped || url;499500 // Relative501 if (!~url.indexOf('://')) {502 // Respect mount-point

tweak res.redirect() mount route logicTj Holowaychukbefore adoption43d9f6e

line 503why, one step back
503 if (0 != url.indexOf(app.route)) url = app.route + url;

new ViewTj Holowaychukbefore adoptione1da383

lines 504–505why, one step back
504
505 // Absolute

tmp fixTj Holowaychukbefore adoption1faba13

lines 506–508why, one step back
506 var host = req.header('Host')
507 , tls = false // TODO: req.secure;508

new ViewTj Holowaychukbefore adoptione1da383

lines 509–558why, one step back
509 url = 'http' + (tls ? 's' : '') + '://' + host + url;
510 }511512 // Support text/{plain,html} by default513 if (req.accepts('html')) {514 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';515 this.header('Content-Type', 'text/html');516 } else {517 body = statusCodes[status] + '. Redirecting to ' + url;518 this.header('Content-Type', 'text/plain');519 }520521 // Respond522 this.statusCode = status;523 this.header('Location', url);524 this.end(head ? null : body);525};526527/**528 * Render `view` with the given `options` and optional callback `fn`.529 * When a callback function is given a response will _not_ be made530 * automatically, otherwise a response of _200_ and _text/html_ is given.531 *532 * Options:533 * 534 * - `status` Response status code (`res.statusCode`)535 * - `charset` Set the charset (`res.charset`)536 *537 * Reserved locals:538 *539 * - `cache` boolean hinting to the engine it should cache540 * - `filename` filename of the view being rendered541 *542 * @param {String} view543 * @param {Object|Function} options or callback function544 * @param {Function} fn545 * @api public546 */547548res.render = function(view, options, fn){549 var self = this550 , options = options || {}551 , req = this.req552 , app = req.app;553554 // support callback function as second arg555 if ('function' == typeof options) {556 fn = options, options = {};557 }558

Added replacement for dynamic locals. Closes #788Tj Holowaychukbefore adoption73f1da2

lines 559–561why, one step back
559 function render() {
560 // merge res.locals561 options.locals = self.locals;

new ViewTj Holowaychukbefore adoptione1da383

line 562why, one step back
562

Added replacement for dynamic locals. Closes #788Tj Holowaychukbefore adoption73f1da2

lines 563–567why, one step back
563 // default callback to respond
564 fn = fn || function(err, str){565 if (err) return req.next(err);566 self.send(str);567 };

new ViewTj Holowaychukbefore adoptione1da383

line 568why, one step back
568

Added replacement for dynamic locals. Closes #788Tj Holowaychukbefore adoption73f1da2

lines 569–578why, one step back
569 // render
570 app.render(view, options, fn);571 }572573 // invoke view callbacks574 var callbacks = app.viewCallbacks575 , pending = callbacks.length576 , len = pending577 , done;578

refactored res.render()Tj Holowaychukbefore adoptionb433550

lines 579–582why, one step back
579 if (len) {
580 for (var i = 0; i < len; ++i) {581 callbacks[i](req, self, function(err){582 if (done) return;

Added replacement for dynamic locals. Closes #788Tj Holowaychukbefore adoption73f1da2

line 583why, one step back
583

refactored res.render()Tj Holowaychukbefore adoptionb433550

lines 584–594why, one step back
584 if (err) {
585 req.next(err);586 done = true;587 return;588 }589590 --pending || render();591 });592 }593 } else {594 render();

Added replacement for dynamic locals. Closes #788Tj Holowaychukbefore adoption73f1da2

line 595why, one step back
595 }

new ViewTj Holowaychukbefore adoptione1da383

line 596why, one step back
596};