Skip to content
Myr

response.js

This file

Path

lib/response.js

598 lines · 13.7 KiB · JavaScript

Last changed by

mergedTj Holowaychukbefore adoption547d18c

History of this file

Take it

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

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};

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

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/**

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

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

mergedTj Holowaychukbefore adoption547d18c

lines 213–214why, one step back
213 // TODO: remove
214 // TODO: remove docs for headerSent?

using connects error code utilTj Holowaychukbefore adoptiona95a0ab

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

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

utilize res.headerSent from connectTj Holowaychukbefore adoption40f8202

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

line 219why, one step back
219

refactoringTj Holowaychukbefore adoptionf68ba2e

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

Added forbidden testsTj Holowaychukbefore adoption2f76226

line 222why, one step back
222

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

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

refactoringTj Holowaychukbefore adoptionf68ba2e

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

lines 225–242why, one step back
225
226 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 has

mergedTj Holowaychukbefore adoption547d18c

line 243why, one step back
243 * ocurred. Be sure to check `res.headerSent` if you plan to respond.

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

lines 244–294why, one step back
244 *
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 back
295 if (filename) this.type(filename);

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

lines 296–364why, one step back
296 this.header('Content-Disposition', filename
297 ? '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){

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

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

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

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

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

lines 368–371why, one step back
368 : opts);
369};370371/**

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

lines 372–389why, one step back
372 * 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/**

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

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

Added relative redirect testTj Holowaychukbefore adoption55ee0a0

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

lines 396–405why, one step back
396 *
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} name

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

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

lines 407–412why, one step back
407 * @param {Options} options
408 * @api public409 */410411res.cookie = function(name, val, options){412 options = options || {};

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

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

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

Fixed res.cookie() path defaultTj Holowaychukbefore adoptionbee0496

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

lines 416–427why, one step back
416 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 redirects427 * to the _Referrer_ or _Referer_ headers or the application's

Added relative redirect testTj Holowaychukbefore adoption55ee0a0

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

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

tweak res.redirect() mount route logicTj Holowaychukbefore adoption43d9f6e

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

lines 475–486why, one step back
475 , head = 'HEAD' == req.method
476 , status = 302477 , body;478479 // allow status / url480 if (2 == arguments.length) {481 status = url;482 url = arguments[1];483 }484485 // Setup redirect map486 var map = {

tweak res.redirect() mount route logicTj Holowaychukbefore adoption43d9f6e

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

lines 489–504why, one step back
489 };
490491 // Support custom redirect map492 map.__proto__ = app.redirects;493494 // Attempt mapped redirect495 var mapped = 'function' == typeof map[url]496 ? map[url](req, this)497 : map[url];498499 // Perform redirect500 url = mapped || url;501502 // Relative503 if (!~url.indexOf('://')) {504 // Respect mount-point

tweak res.redirect() mount route logicTj Holowaychukbefore adoption43d9f6e

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

lines 506–507why, one step back
506
507 // Absolute

tmp fixTj Holowaychukbefore adoption1faba13

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

lines 511–560why, one step back
511 url = 'http' + (tls ? 's' : '') + '://' + host + url;
512 }513514 // Support text/{plain,html} by default515 if (req.accepts('html')) {516 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';517 this.header('Content-Type', 'text/html');518 } else {519 body = statusCodes[status] + '. Redirecting to ' + url;520 this.header('Content-Type', 'text/plain');521 }522523 // Respond524 this.statusCode = status;525 this.header('Location', url);526 this.end(head ? null : body);527};528529/**530 * Render `view` with the given `options` and optional callback `fn`.531 * When a callback function is given a response will _not_ be made532 * automatically, otherwise a response of _200_ and _text/html_ is given.533 *534 * Options:535 * 536 * - `status` Response status code (`res.statusCode`)537 * - `charset` Set the charset (`res.charset`)538 *539 * Reserved locals:540 *541 * - `cache` boolean hinting to the engine it should cache542 * - `filename` filename of the view being rendered543 *544 * @param {String} view545 * @param {Object|Function} options or callback function546 * @param {Function} fn547 * @api public548 */549550res.render = function(view, options, fn){551 var self = this552 , options = options || {}553 , req = this.req554 , app = req.app;555556 // support callback function as second arg557 if ('function' == typeof options) {558 fn = options, options = {};559 }560

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

lines 561–563why, one step back
561 function render() {
562 // merge res.locals563 options.locals = self.locals;

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

line 564why, one step back
564

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

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

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

line 570why, one step back
570

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

lines 571–580why, one step back
571 // render
572 app.render(view, options, fn);573 }574575 // invoke view callbacks576 var callbacks = app.viewCallbacks577 , pending = callbacks.length578 , len = pending579 , done;580

refactored res.render()Tj Holowaychukbefore adoptionb433550

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

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

line 585why, one step back
585

refactored res.render()Tj Holowaychukbefore adoptionb433550

lines 586–596why, one step back
586 if (err) {
587 req.next(err);588 done = true;589 return;590 }591592 --pending || render();593 });594 }595 } else {596 render();

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

line 597why, one step back
597 }

re-implemented "view cache"Tj Holowaychukbefore adoption8a38211

line 598why, one step back
598};