Skip to content
Myr

response.js

This file

Path

lib/response.js

588 lines · 13.5 KiB · JavaScript

Last changed by

Added res.cache(str)Tj Holowaychukbefore adoptioncaec590

History of this file

Take it

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

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(str)Tj Holowaychukbefore adoptioncaec590

lines 45–56why, one step back
45 * Set Cache-Control to the given `str`.
46 *47 * @param {String} str48 * @return {ServerResponse}49 * @api public50 */5152res.cache = function(str){53 return this.set('Cache-Control', str);54};5556/**

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 57–73why, one step back
57 * Send a response.
58 *59 * Examples:60 *61 * res.send(new Buffer('wahoo'));62 * res.send({ some: 'json' });63 * res.send('<p>some html</p>');64 * res.send(404, 'Sorry, cant find that');65 * res.send(404);66 *67 * @param {Mixed} body or status68 * @param {Mixed} body69 * @return {ServerResponse}70 * @api public71 */7273res.send = function(body){

refactored `res.send()`Tj Holowaychukbefore adoption2c734e2

lines 74–76why, one step back
74 var req = this.req
75 , head = 'HEAD' == req.method;76

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 77–123why, one step back
77 // allow status / body
78 if (2 == arguments.length) {79 this.statusCode = body;80 body = arguments[1];81 }8283 switch (typeof body) {84 // response status85 case 'number':86 this.header('Content-Type') || this.contentType('.txt');87 this.statusCode = body;88 body = http.STATUS_CODES[body];89 break;90 // string defaulting to html91 case 'string':92 if (!this.header('Content-Type')) {93 this.charset = this.charset || 'utf-8';94 this.contentType('.html');95 }96 break;97 case 'boolean':98 case 'object':99 if (null == body) {100 body = '';101 } else if (Buffer.isBuffer(body)) {102 this.header('Content-Type') || this.contentType('.bin');103 } else {104 return this.json(body);105 }106 break;107 }108109 // populate Content-Length110 if (undefined !== body && !this.header('Content-Length')) {111 this.header('Content-Length', Buffer.isBuffer(body)112 ? body.length113 : Buffer.byteLength(body));114 }115116 // strip irrelevant headers117 if (204 == this.statusCode || 304 == this.statusCode) {118 this.removeHeader('Content-Type');119 this.removeHeader('Content-Length');120 body = '';121 }122123 // respond

refactored `res.send()`Tj Holowaychukbefore adoption2c734e2

line 124why, one step back
124 this.end(head ? null : body);

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 125–200why, one step back
125 return this;
126};127128/**129 * Send JSON response.130 *131 * Examples:132 *133 * res.json(null);134 * res.json({ user: 'tj' });135 * res.json(500, 'oh noes!');136 * res.json(404, 'I dont have that');137 *138 * @param {Mixed} obj or status139 * @param {Mixed} obj140 * @return {ServerResponse}141 * @api public142 */143144res.json = function(obj){145 // allow status / body146 if (2 == arguments.length) {147 this.statusCode = obj;148 obj = arguments[1];149 }150151 var body = JSON.stringify(obj)152 , callback = this.req.query.callback153 , jsonp = this.app.enabled('jsonp callback');154155 this.charset = this.charset || 'utf-8';156 this.header('Content-Type', 'application/json');157158 if (callback && jsonp) {159 this.header('Content-Type', 'text/javascript');160 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';161 }162163 return this.send(body);164};165166/**167 * Transfer the file at the given `path`.168 * 169 * Automatically sets the _Content-Type_ response header field.170 * The callback `fn(err)` is invoked when the transfer is complete171 * or when an error occurs. Be sure to check `res.sentHeader`172 * if you wish to attempt responding, as the header and some data173 * may have already been transferred.174 *175 * Options:176 *177 * - `maxAge` defaulting to 0178 * - `root` root directory for relative filenames179 *180 * @param {String} path181 * @param {Object|Function} options or fn182 * @param {Function} fn183 * @api public184 */185186res.sendfile = function(path, options, fn){187 var self = this188 , req = self.req189 , next = this.req.next190 , options = options || {};191192 // support function as second arg193 if ('function' == typeof options) {194 fn = options;195 options = {};196 }197198 // callback199 options.callback = function(err){200 if (err) {

refactoringTj Holowaychukbefore adoptionf68ba2e

lines 201–204why, one step back
201 // cast ENOENT
202 if ('ENOENT' == err.code) err = 404;203204 // coerce numeric error to an Error

using connects error code utilTj Holowaychukbefore adoptiona95a0ab

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

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

utilize res.headerSent from connectTj Holowaychukbefore adoption40f8202

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

line 209why, one step back
209

refactoringTj Holowaychukbefore adoptionf68ba2e

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

Added forbidden testsTj Holowaychukbefore adoption2f76226

line 212why, one step back
212

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

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

refactoringTj Holowaychukbefore adoptionf68ba2e

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 215–263why, one step back
215
216 return req.next(err);217 }218219 fn && fn();220 };221222 // transfer223 options.path = encodeURIComponent(path);224 send(this.req, this, next, options);225};226227/**228 * Transfer the file at the given `path` as an attachment.229 *230 * Optionally providing an alternate attachment `filename`,231 * and optional callback `fn(err)`. The callback is invoked232 * when the data transfer is complete, or when an error has233 * ocurred. Be sure to check `res.sendHeader` if you plan to respond.234 *235 * @param {String} path236 * @param {String|Function} filename or fn237 * @param {Function} fn238 * @api public239 */240241res.download = function(path, filename, fn){242 // support function as second arg243 if ('function' == typeof filename) {244 fn = filename;245 filename = null;246 }247248 return this.attachment(filename || path).sendfile(path, fn);249};250251/**252 * Set _Content-Type_ response header passed through `mime.lookup()`.253 *254 * Examples:255 *256 * var filename = 'path/to/image.png';257 * res.contentType(filename);258 * // res.headers['Content-Type'] is now "image/png"259 *260 * res.contentType('.html');261 * res.contentType('html');262 * res.contentType('json');263 * res.contentType('png');

Added res.type() alias of res.contentType()Tj Holowaychukbefore adoption54c1a20

line 264why, one step back
264 * res.type('png');

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 265–270why, one step back
265 *
266 * @param {String} type267 * @return {ServerResponse} for chaining268 * @api public269 */270

Added res.type() alias of res.contentType()Tj Holowaychukbefore adoption54c1a20

lines 271–272why, one step back
271res.contentType =
272res.type = function(type){

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 273–284why, one step back
273 return this.header('Content-Type', mime.lookup(type));
274};275276/**277 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.278 *279 * @param {String} filename280 * @return {ServerResponse}281 * @api public282 */283284res.attachment = function(filename){

misc refactoringTj Holowaychukbefore adoption4b0b55c

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 286–292why, one step back
286 this.header('Content-Disposition', filename
287 ? 'attachment; filename="' + basename(filename) + '"'288 : 'attachment');289 return this;290};291292/**

Added support for `res.set(obj)`. Closes #834Tj Holowaychukbefore adoption021655a

lines 293–294why, one step back
293 * Set header `field` to `val`, or pass
294 * an object of of header fields.

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

line 295why, one step back
295 *

Added support for `res.set(obj)`. Closes #834Tj Holowaychukbefore adoption021655a

lines 296–301why, one step back
296 * Examples:
297 *298 * res.set('Accept', 'application/json');299 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });300 *301 * @param {String|Object} field

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 302–307why, one step back
302 * @param {String} val
303 * @return {ServerResponse} for chaining304 * @api public305 */306307res.set = function(field, val){

Added support for `res.set(obj)`. Closes #834Tj Holowaychukbefore adoption021655a

lines 308–314why, one step back
308 if (2 == arguments.length) {
309 this.setHeader(field, val);310 } else {311 for (var key in field) {312 this.setHeader(key, field[key]);313 }314 }

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 315–354why, one step back
315 return this;
316};317318/**319 * Get value for header `field`.320 *321 * @param {String} field322 * @return {String}323 * @api public324 */325326res.get = function(field){327 return this.getHeader(field);328};329330/**331 * Set or get response header `field` with optional `val`.332 *333 * @param {String} name334 * @param {String} val335 * @return {ServerResponse} for chaining336 * @api public337 */338339res.header = function(field, val){340 if (1 == arguments.length) return this.getHeader(field);341 this.setHeader(field, val);342 return this;343};344345/**346 * Clear cookie `name`.347 *348 * @param {String} name349 * @param {Object} options350 * @param {ServerResponse} for chaining351 * @api public352 */353354res.clearCookie = function(name, options){

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

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

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

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

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 358–361why, one step back
358 : opts);
359};360361/**

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

lines 362–379why, one step back
362 * Set a signed cookie with the given `name` and `val`.
363 * See `res.cookie()` for details.364 *365 * @param {String} name366 * @param {String|Object} val367 * @param {Object} options368 * @api public369 */370371res.signedCookie = function(name, val, options){372 var secret = this.req.secret;373 if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');374 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);375 val = utils.sign(val, secret);376 return this.cookie(name, val, options);377};378379/**

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 380–384why, one step back
380 * Set cookie `name` to `val`, with the given `options`.
381 *382 * Options:383 *384 * - `maxAge` max-age in milliseconds, converted to `expires`

Added relative redirect testTj Holowaychukbefore adoption55ee0a0

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 386–395why, one step back
386 *
387 * Examples:388 *389 * // "Remember Me" for 15 minutes390 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });391 *392 * // save as above393 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })394 *395 * @param {String} name

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

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 397–402why, one step back
397 * @param {Options} options
398 * @api public399 */400401res.cookie = function(name, val, options){402 options = options || {};

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

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

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

Fixed res.cookie() path defaultTj Holowaychukbefore adoptionbee0496

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 406–412why, one step back
406 var cookie = utils.serializeCookie(name, val, options);
407 this.header('Set-Cookie', cookie);408 return this;409};410411/**412 * Redirect to the given `url` with optional response `status`

Changed `res.redirect()` signature to accept status first. Closes #832Tj Holowaychukbefore adoptione301d43

line 413why, one step back
413 * defaulting to 302.

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 414–417why, one step back
414 *
415 * The given `url` can also be the name of a mapped url, for416 * example by default express supports "back" which redirects417 * to the _Referrer_ or _Referer_ headers or the application's

Added relative redirect testTj Holowaychukbefore adoption55ee0a0

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

line 420why, one step back
420 *

Changed `res.redirect()` signature to accept status first. Closes #832Tj Holowaychukbefore adoptione301d43

lines 421–426why, one step back
421 * Examples:
422 *423 * res.redirect('/foo/bar');424 * res.redirect('http://example.com');425 * res.redirect(301, 'http://example.com');426 *

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

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

Changed `res.redirect()` signature to accept status first. Closes #832Tj Holowaychukbefore adoptione301d43

line 461why, one step back
461res.redirect = function(url){

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 462–463why, one step back
462 var app = this.app
463 , req = this.req

tweak res.redirect() mount route logicTj Holowaychukbefore adoption43d9f6e

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

Fixed `res.redirect()` HEAD supportTj Holowaychukbefore adoptiond3937b9

line 465why, one step back
465 , head = 'HEAD' == req.method

Changed `res.redirect()` signature to accept status first. Closes #832Tj Holowaychukbefore adoptione301d43

line 466why, one step back
466 , status = 302

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

line 467why, one step back
467 , body;

Changed `res.redirect()` signature to accept status first. Closes #832Tj Holowaychukbefore adoptione301d43

lines 468–473why, one step back
468
469 // allow status / url470 if (2 == arguments.length) {471 status = url;472 url = arguments[1];473 }

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 474–476why, one step back
474
475 // Setup redirect map476 var map = {

tweak res.redirect() mount route logicTj Holowaychukbefore adoption43d9f6e

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 479–494why, one step back
479 };
480481 // Support custom redirect map482 map.__proto__ = app.redirects;483484 // Attempt mapped redirect485 var mapped = 'function' == typeof map[url]486 ? map[url](req, this)487 : map[url];488489 // Perform redirect490 url = mapped || url;491492 // Relative493 if (!~url.indexOf('://')) {494 // Respect mount-point

tweak res.redirect() mount route logicTj Holowaychukbefore adoption43d9f6e

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 496–497why, one step back
496
497 // Absolute

tmp fixTj Holowaychukbefore adoption1faba13

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

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

lines 501–515why, one step back
501 url = 'http' + (tls ? 's' : '') + '://' + host + url;
502 }503504 // Support text/{plain,html} by default505 if (req.accepts('html')) {506 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';507 this.header('Content-Type', 'text/html');508 } else {509 body = statusCodes[status] + '. Redirecting to ' + url;510 this.header('Content-Type', 'text/plain');511 }512513 // Respond514 this.statusCode = status;515 this.header('Location', url);

Fixed `res.redirect()` HEAD supportTj Holowaychukbefore adoptiond3937b9

line 516why, one step back
516 this.end(head ? null : body);

removed app.helpers() use app.locals()Tj Holowaychukbefore adoption81f3111

line 517why, one step back
517};

request-level render()Tj Holowaychukbefore adoptionc40c54f

lines 518–541why, one step back
518
519/**520 * Render `view` with the given `options` and optional callback `fn`.521 * When a callback function is given a response will _not_ be made522 * automatically, otherwise a response of _200_ and _text/html_ is given.523 *524 * Options:525 * 526 * - `status` Response status code (`res.statusCode`)527 * - `charset` Set the charset (`res.charset`)528 *529 * Reserved locals:530 *531 * - `cache` boolean hinting to the engine it should cache532 * - `filename` filename of the view being rendered533 *534 * @param {String} view535 * @param {Object|Function} options or callback function536 * @param {Function} fn537 * @api public538 */539540res.render = function(view, options, fn){541 var self = this

merging res.localsTj Holowaychukbefore adoption98e2c05

line 542why, one step back
542 , options = options || {}

request-level render()Tj Holowaychukbefore adoptionc40c54f

lines 543–547why, one step back
543 , req = this.req
544 , app = req.app;545546 // support callback function as second arg547 if ('function' == typeof options) {

typoTj Holowaychukbefore adoptionae11d83

line 548why, one step back
548 fn = options, options = {};

request-level render()Tj Holowaychukbefore adoptionc40c54f

line 549why, one step back
549 }

merging res.localsTj Holowaychukbefore adoption98e2c05

line 550why, one step back
550

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

lines 551–553why, one step back
551 function render() {
552 // merge res.locals553 options.locals = self.locals;

request-level render()Tj Holowaychukbefore adoptionc40c54f

line 554why, one step back
554

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

lines 555–559why, one step back
555 // default callback to respond
556 fn = fn || function(err, str){557 if (err) return req.next(err);558 self.send(str);559 };

request-level render()Tj Holowaychukbefore adoptionc40c54f

line 560why, one step back
560

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

lines 561–570why, one step back
561 // render
562 app.render(view, options, fn);563 }564565 // invoke view callbacks566 var callbacks = app.viewCallbacks567 , pending = callbacks.length568 , len = pending569 , done;570

refactored res.render()Tj Holowaychukbefore adoptionb433550

lines 571–574why, one step back
571 if (len) {
572 for (var i = 0; i < len; ++i) {573 callbacks[i](req, self, function(err){574 if (done) return;

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

line 575why, one step back
575

refactored res.render()Tj Holowaychukbefore adoptionb433550

lines 576–586why, one step back
576 if (err) {
577 req.next(err);578 done = true;579 return;580 }581582 --pending || render();583 });584 }585 } else {586 render();

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

line 587why, one step back
587 }

request-level render()Tj Holowaychukbefore adoptionc40c54f

line 588why, one step back
588};