Skip to content
Myr

response.js

This file

Path

lib/response.js

437 lines · 10.1 KiB · JavaScript

Last changed by

Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2

History of this file

Take it

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

miscTj Holowaychukbefore adoption6bef3ef

lines 1–16why, 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.utils

refactored `res.redirect()` slightlyTj Holowaychukbefore adoption6bd5182

line 17why, one step back
17 , statusCodes = http.STATUS_CODES

miscTj Holowaychukbefore adoption6bef3ef

lines 18–20why, one step back
18 , parseRange = require('./utils').parseRange
19 , res = http.ServerResponse.prototype20 , send = connect.static.send

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 21–23why, one step back
21 , mime = require('mime')
22 , basename = path.basename23 , join = path.join;

miscTj Holowaychukbefore adoption6bef3ef

lines 24–25why, one step back
24
25/**

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 26why, one step back
26 * Send a response.

miscTj Holowaychukbefore adoption6bef3ef

lines 27–32why, one step back
27 *
28 * Examples:29 *30 * res.send(new Buffer('wahoo'));31 * res.send({ some: 'json' });32 * res.send('<p>some html</p>');

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 33why, one step back
33 * res.send(404, 'Sorry, cant find that');

miscTj Holowaychukbefore adoption6bef3ef

lines 34–35why, one step back
34 * res.send(404);
35 *

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

lines 36–37why, one step back
36 * @param {Mixed} body or status
37 * @param {Mixed} body

miscTj Holowaychukbefore adoption6bef3ef

lines 38–41why, one step back
38 * @return {ServerResponse}
39 * @api public40 */41

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

lines 42–47why, one step back
42res.send = function(body){
43 // allow status / body44 if (2 == arguments.length) {45 this.statusCode = body;46 body = arguments[1];47 }

miscTj Holowaychukbefore adoption6bef3ef

lines 48–49why, one step back
48
49 switch (typeof body) {

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 50why, one step back
50 // response status

miscTj Holowaychukbefore adoption6bef3ef

line 51why, one step back
51 case 'number':

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

lines 52–54why, one step back
52 this.header('Content-Type') || this.contentType('.txt');
53 this.statusCode = body;54 body = http.STATUS_CODES[body];

miscTj Holowaychukbefore adoption6bef3ef

line 55why, one step back
55 break;

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 56why, one step back
56 // string defaulting to html

miscTj Holowaychukbefore adoption6bef3ef

lines 57–64why, one step back
57 case 'string':
58 if (!this.header('Content-Type')) {59 this.charset = this.charset || 'utf-8';60 this.contentType('.html');61 }62 break;63 case 'boolean':64 case 'object':

Changed `res.send(null)` responds with empty stringTj Holowaychukbefore adoption376bedf

lines 65–67why, one step back
65 if (null == body) {
66 body = '';67 } else if (Buffer.isBuffer(body)) {

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 68why, one step back
68 this.header('Content-Type') || this.contentType('.bin');

miscTj Holowaychukbefore adoption6bef3ef

line 69why, one step back
69 } else {

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 70why, one step back
70 return this.json(body);

miscTj Holowaychukbefore adoption6bef3ef

lines 71–75why, one step back
71 }
72 break;73 }7475 // populate Content-Length

Fixed [23]04 supportTj Holowaychukbefore adoption5ac5352

line 76why, one step back
76 if (undefined !== body && !this.header('Content-Length')) {

miscTj Holowaychukbefore adoption6bef3ef

lines 77–82why, one step back
77 this.header('Content-Length', Buffer.isBuffer(body)
78 ? body.length79 : Buffer.byteLength(body));80 }8182 // strip irrelevant headers

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 83why, one step back
83 if (204 == this.statusCode || 304 == this.statusCode) {

miscTj Holowaychukbefore adoption6bef3ef

lines 84–85why, one step back
84 this.removeHeader('Content-Type');
85 this.removeHeader('Content-Length');

Fixed 204 / 304 responsesTj Holowaychukbefore adoptionc631eb4

line 86why, one step back
86 body = '';

miscTj Holowaychukbefore adoption6bef3ef

lines 87–90why, one step back
87 }
8889 // respond90 this.end('HEAD' == this.req.method ? undefined : body);

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 91–94why, one step back
91 return this;
92};9394/**

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 95why, one step back
95 * Send JSON response.

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 96–100why, one step back
96 *
97 * Examples:98 *99 * res.json(null);100 * res.json({ user: 'tj' });

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

lines 101–102why, one step back
101 * res.json(500, 'oh noes!');
102 * res.json(404, 'I dont have that');

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

line 103why, one step back
103 *

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 104why, one step back
104 * @param {Mixed} obj or status

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 105–109why, one step back
105 * @param {Mixed} obj
106 * @return {ServerResponse}107 * @api public108 */109

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

lines 110–116why, one step back
110res.json = function(obj){
111 // allow status / body112 if (2 == arguments.length) {113 this.statusCode = obj;114 obj = arguments[1];115 }116

Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd

lines 117–120why, one step back
117 var body = JSON.stringify(obj)
118 , callback = this.req.query.callback119 , jsonp = this.app.enabled('jsonp callback');120

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 121–122why, one step back
121 this.charset = this.charset || 'utf-8';
122 this.header('Content-Type', 'application/json');

Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd

lines 123–125why, one step back
123
124 if (callback && jsonp) {125 this.header('Content-Type', 'text/javascript');

Revert "removed jsonp stripping"Tj Holowaychukbefore adoption60d16ea

line 126why, one step back
126 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';

Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd

lines 127–128why, one step back
127 }
128

Changed `res.{send,json}()` status code to the first arg at all timesTj Holowaychukbefore adoptionc35cd7f

line 129why, one step back
129 return this.send(body);

miscTj Holowaychukbefore adoption6bef3ef

lines 130–131why, one step back
130};
131

docs for res.status()Tj Holowaychukbefore adoption9477c9b

lines 132–139why, one step back
132/**
133 * Set status `code`.134 *135 * @param {Number} code136 * @return {ServerResponse}137 * @api public138 */139

Added chainable res.status(code)Tj Holowaychukbefore adoptionb04be51

lines 140–144why, one step back
140res.status = function(code){
141 this.statusCode = code;142 return this;143};144

miscTj Holowaychukbefore adoption6bef3ef

lines 145–170why, one step back
145/**
146 * Transfer the file at the given `path`. Automatically sets 147 * the _Content-Type_ response header field. `next()` is called148 * when `path` is a directory, or when an error occurs.149 *150 * Options:151 *152 * - `maxAge` defaulting to 0153 * - `root` root directory for relative filenames154 *155 * @param {String} path156 * @param {Object|Function} options or fn157 * @param {Function} fn158 * @api public159 */160161res.sendfile = function(path, options, fn){162 var next = this.req.next;163 options = options || {};164165 // support function as second arg166 if ('function' == typeof options) {167 fn = options;168 options = {};169 }170

Fixed res.sendfile() bug preventing the transfer of files with spacesTj Holowaychukbefore adoptionc6d7608

line 171why, one step back
171 options.path = encodeURIComponent(path);

miscTj Holowaychukbefore adoption6bef3ef

lines 172–190why, one step back
172 options.callback = fn;
173 send(this.req, this, next, options);174};175176/**177 * Set _Content-Type_ response header passed through `mime.lookup()`.178 *179 * Examples:180 *181 * var filename = 'path/to/image.png';182 * res.contentType(filename);183 * // res.headers['Content-Type'] is now "image/png"184 *185 * res.contentType('.html');186 * res.contentType('html');187 * res.contentType('json');188 * res.contentType('png');189 *190 * @param {String} type

docsTj Holowaychukbefore adoptionbb9d505

line 191why, one step back
191 * @return {ServerResponse} for chaining

miscTj Holowaychukbefore adoption6bef3ef

lines 192–209why, one step back
192 * @api public
193 */194195res.contentType = function(type){196 return this.header('Content-Type', mime.lookup(type));197};198199/**200 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.201 *202 * @param {String} filename203 * @return {ServerResponse}204 * @api public205 */206207res.attachment = function(filename){208 if (filename) this.contentType(filename);209 this.header('Content-Disposition', filename

misc refactoringTj Holowaychukbefore adoption70e6baf

line 210why, one step back
210 ? 'attachment; filename="' + basename(filename) + '"'

miscTj Holowaychukbefore adoption6bef3ef

lines 211–218why, one step back
211 : 'attachment');
212 return this;213};214215/**216 * Transfer the file at the given `path`, with optional 217 * `filename` as an attachment and optional callback `fn(err)`,218 * and optional `fn2(err)` which is invoked when an error has

typoTj Holowaychukbefore adoption0cbb1f6

line 219why, one step back
219 * occurred after header has been sent.

miscTj Holowaychukbefore adoption6bef3ef

lines 220–256why, one step back
220 *
221 * @param {String} path222 * @param {String|Function} filename or fn223 * @param {Function} fn224 * @param {Function} fn2225 * @api public226 */227228res.download = function(path, filename, fn, fn2){229 var self = this;230231 // support callback as second arg232 if ('function' == typeof filename) {233 fn2 = fn;234 fn = filename;235 filename = null;236 }237238 // transfer the file239 this.attachment(filename || path).sendfile(path, function(err){240 var sentHeader = self._header;241 if (err) {242 if (!sentHeader) self.removeHeader('Content-Disposition');243 if (sentHeader) {244 fn2 && fn2(err);245 } else if (fn) {246 fn(err);247 } else {248 self.req.next(err);249 }250 } else if (fn) {251 fn();252 }253 });254};255256/**

Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2

line 257why, one step back
257 * Set header `field` to `val`.

Added `res.set(field, val)` as an alternative to `res.header()`Tj Holowaychukbefore adoption19a1a22

line 258why, one step back
258 *

Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2

line 259why, one step back
259 * @param {String} field

Added `res.set(field, val)` as an alternative to `res.header()`Tj Holowaychukbefore adoption19a1a22

lines 260–264why, one step back
260 * @param {String} val
261 * @return {ServerResponse} for chaining262 * @api public263 */264

Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2

lines 265–266why, one step back
265res.set = function(field, val){
266 this.setHeader(field, val);

Added `res.set(field, val)` as an alternative to `res.header()`Tj Holowaychukbefore adoption19a1a22

lines 267–270why, one step back
267 return this;
268};269270/**

Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2

line 271why, one step back
271 * Get value for header `field`.

miscTj Holowaychukbefore adoption6bef3ef

line 272why, one step back
272 *

Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2

lines 273–284why, one step back
273 * @param {String} field
274 * @return {String}275 * @api public276 */277278res.get = function(field){279 return this.getHeader(field);280};281282/**283 * Set or get response header `field` with optional `val`.284 *

miscTj Holowaychukbefore adoption6bef3ef

lines 285–286why, one step back
285 * @param {String} name
286 * @param {String} val

Merge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135

line 287why, one step back
287 * @return {ServerResponse} for chaining

miscTj Holowaychukbefore adoption6bef3ef

lines 288–290why, one step back
288 * @api public
289 */290

Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2

lines 291–293why, one step back
291res.header = function(field, val){
292 if (1 == arguments.length) return this.getHeader(field);293 this.setHeader(field, val);

Refactored `res.header()`Tj Holowaychukbefore adoption54d3751

line 294why, one step back
294 return this;

miscTj Holowaychukbefore adoption6bef3ef

lines 295–301why, one step back
295};
296297/**298 * Clear cookie `name`.299 *300 * @param {String} name301 * @param {Object} options

Changed `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8

line 302why, one step back
302 * @param {ServerResponse} for chaining

miscTj Holowaychukbefore adoption6bef3ef

lines 303–307why, one step back
303 * @api public
304 */305306res.clearCookie = function(name, options){307 var opts = { expires: new Date(1) };

Changed `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8

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

miscTj Holowaychukbefore adoption6bef3ef

lines 309–318why, one step back
309 ? utils.merge(options, opts)
310 : opts);311};312313/**314 * Set cookie `name` to `val`, with the given `options`.315 *316 * Options:317 *318 * - `maxAge` max-age in milliseconds, converted to `expires`

Changed; default cookie path to "home" setting. Closes #731Tj Holowaychukbefore adoption09c9452

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

miscTj Holowaychukbefore adoption6bef3ef

lines 320–337why, one step back
320 *
321 * Examples:322 *323 * // "Remember Me" for 15 minutes324 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });325 *326 * // save as above327 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })328 *329 * @param {String} name330 * @param {String} val331 * @param {Options} options332 * @api public333 */334335res.cookie = function(name, val, options){336 options = options || {};337 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);

when cookie path === null dont default itTj Holowaychukbefore adoptionee4471b

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

miscTj Holowaychukbefore adoption6bef3ef

lines 339–340why, one step back
339 var cookie = utils.serializeCookie(name, val, options);
340 this.header('Set-Cookie', cookie);

Changed `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8

line 341why, one step back
341 return this;

miscTj Holowaychukbefore adoption6bef3ef

lines 342–415why, one step back
342};
343344/**345 * Redirect to the given `url` with optional response `status`346 * defauling to 302.347 *348 * The given `url` can also be the name of a mapped url, for349 * example by default express supports "back" which redirects350 * to the _Referrer_ or _Referer_ headers or the application's351 * "home" setting. Express also supports "home" out of the box,352 * which can be set via `app.set('home', '/blog');`, and defaults353 * to '/'.354 *355 * Redirect Mapping:356 * 357 * To extend the redirect mapping capabilities that Express provides,358 * we may use the `app.redirect()` method:359 * 360 * app.redirect('google', 'http://google.com');361 * 362 * Now in a route we may call:363 *364 * res.redirect('google');365 *366 * We may also map dynamic redirects:367 *368 * app.redirect('comments', function(req, res){369 * return '/post/' + req.params.id + '/comments';370 * });371 *372 * So now we may do the following, and the redirect will dynamically adjust to373 * the context of the request. If we called this route with _GET /post/12_ our374 * redirect _Location_ would be _/post/12/comments_.375 *376 * app.get('/post/:id', function(req, res){377 * res.redirect('comments');378 * });379 *380 * Unless an absolute `url` is given, the app's mount-point381 * will be respected. For example if we redirect to `/posts`,382 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.383 *384 * @param {String} url385 * @param {Number} code386 * @api public387 */388389res.redirect = function(url, status){390 var app = this.app391 , req = this.req392 , base = app.set('home') || '/'393 , status = status || 302394 , body;395396 // Setup redirect map397 var map = {398 back: req.header('Referrer', base)399 , home: base400 };401402 // Support custom redirect map403 map.__proto__ = app.redirects;404405 // Attempt mapped redirect406 var mapped = 'function' == typeof map[url]407 ? map[url](req, this)408 : map[url];409410 // Perform redirect411 url = mapped || url;412413 // Relative414 if (!~url.indexOf('://')) {415 // Respect mount-point

misc refactorTj Holowaychukbefore adoption490584c

line 416why, one step back
416 if (app.route) url = join(app.route, url);

miscTj Holowaychukbefore adoption6bef3ef

lines 417–425why, one step back
417
418 // Absolute419 var host = req.headers.host420 , tls = req.connection.encrypted;421 url = 'http' + (tls ? 's' : '') + '://' + host + url;422 }423424 // Support text/{plain,html} by default425 if (req.accepts('html')) {

refactored `res.redirect()` slightlyTj Holowaychukbefore adoption6bd5182

line 426why, one step back
426 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';

miscTj Holowaychukbefore adoption6bef3ef

lines 427–428why, one step back
427 this.header('Content-Type', 'text/html');
428 } else {

refactored `res.redirect()` slightlyTj Holowaychukbefore adoption6bd5182

line 429why, one step back
429 body = statusCodes[status] + '. Redirecting to ' + url;

miscTj Holowaychukbefore adoption6bef3ef

lines 430–437why, one step back
430 this.header('Content-Type', 'text/plain');
431 }432433 // Respond434 this.statusCode = status;435 this.header('Location', url);436 this.end(body);437};