Skip to content
Myr

response.js

This file

Path

lib/response.js

453 lines · 10.6 KiB · JavaScript

Last changed by

refactored `res.send()`Tj Holowaychukbefore adoption2c734e2

History of this file

Take it

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 18–25why, one step back
18 , parseRange = require('./utils').parseRange
19 , res = http.ServerResponse.prototype20 , send = connect.static.send21 , mime = require('mime')22 , basename = path.basename23 , join = path.join;2425/**

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

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

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');

Release 2.3.7Tj Holowaychukbefore adoption44eae73

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

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

line 42why, one step back
42res.send = function(body){

refactored `res.send()`Tj Holowaychukbefore adoption2c734e2

lines 43–45why, one step back
43 var req = this.req
44 , head = 'HEAD' == req.method;45

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

lines 46–50why, one step back
46 // allow status / body
47 if (2 == arguments.length) {48 this.statusCode = body;49 body = arguments[1];50 }

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 51–52why, one step back
51
52 switch (typeof body) {

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

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

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

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

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

line 58why, one step back
58 break;

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

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

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

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

lines 68–70why, one step back
68 if (null == body) {
69 body = '';70 } else if (Buffer.isBuffer(body)) {

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

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

line 72why, one step back
72 } else {

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

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 74–78why, one step back
74 }
75 break;76 }7778 // populate Content-Length

Fixed [23]04 supportTj Holowaychukbefore adoption5ac5352

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 80–85why, one step back
80 this.header('Content-Length', Buffer.isBuffer(body)
81 ? body.length82 : Buffer.byteLength(body));83 }8485 // strip irrelevant headers

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

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

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

Fixed 204 / 304 responsesTj Holowaychukbefore adoptionc631eb4

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 90–92why, one step back
90 }
9192 // respond

refactored `res.send()`Tj Holowaychukbefore adoption2c734e2

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

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

lines 94–97why, one step back
94 return this;
95};9697/**

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

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

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

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

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

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

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

line 106why, one step back
106 *

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

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

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

lines 108–112why, one step back
108 * @param {Mixed} obj
109 * @return {ServerResponse}110 * @api public111 */112

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

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

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

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

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

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

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

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

Revert "removed jsonp stripping"Tj Holowaychukbefore adoption60d16ea

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

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

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

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

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 133–134why, one step back
133};
134

docs for res.status()Tj Holowaychukbefore adoption9477c9b

lines 135–142why, one step back
135/**
136 * Set status `code`.137 *138 * @param {Number} code139 * @return {ServerResponse}140 * @api public141 */142

Added chainable res.status(code)Tj Holowaychukbefore adoptionb04be51

lines 143–147why, one step back
143res.status = function(code){
144 this.statusCode = code;145 return this;146};147

Release 2.3.7Tj Holowaychukbefore adoption44eae73

line 148why, one step back
148/**

refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be

lines 149–152why, one step back
149 * Transfer the file at the given `path`.
150 * 151 * Automatically sets the _Content-Type_ response header field.152 * The callback `fn(err)` is invoked when the transfer is complete

make `res.sendfile()` more like `res.download()`. Closes #774Tj Holowaychukbefore adoption7a476fc

line 153why, one step back
153 * or when an error occurs. Be sure to check `res.sentHeader`

refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be

lines 154–155why, one step back
154 * if you wish to attempt responding, as the header and some data
155 * may have already been transferred.

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 156–168why, one step back
156 *
157 * Options:158 *159 * - `maxAge` defaulting to 0160 * - `root` root directory for relative filenames161 *162 * @param {String} path163 * @param {Object|Function} options or fn164 * @param {Function} fn165 * @api public166 */167168res.sendfile = function(path, options, fn){

refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be

line 169why, one step back
169 var self = this

fixed `res.sendfile()` 404 supportTj Holowaychukbefore adoptiond2df055

line 170why, one step back
170 , req = self.req

refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be

lines 171–172why, one step back
171 , next = this.req.next
172 , options = options || {};

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 173–179why, one step back
173
174 // support function as second arg175 if ('function' == typeof options) {176 fn = options;177 options = {};178 }179

refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be

lines 180–182why, one step back
180 // callback
181 options.callback = function(err){182 // TODO: remove when node adds this

make `res.sendfile()` more like `res.download()`. Closes #774Tj Holowaychukbefore adoption7a476fc

lines 183–189why, one step back
183 self.sentHeader = !! self._header;
184185 // error186 if (err) {187 // ditch content-disposition to prevent funky responses188 if (!self.sentHeader) self.removeHeader('Content-Disposition');189

fixed `res.sendfile()` 404 supportTj Holowaychukbefore adoptiond2df055

lines 190–192why, one step back
190 // not found
191 if ('ENOENT' == err.code) return req.next();192

make `res.sendfile()` more like `res.download()`. Closes #774Tj Holowaychukbefore adoption7a476fc

lines 193–198why, one step back
193 // lost in limbo if there's no callback
194 if (self.sentHeader) return fn && fn(err);195196 // callback available197 if (fn) return fn(err);198

fixed `res.sendfile()` 404 supportTj Holowaychukbefore adoptiond2df055

line 199why, one step back
199 return req.next(err);

make `res.sendfile()` more like `res.download()`. Closes #774Tj Holowaychukbefore adoption7a476fc

lines 200–202why, one step back
200 }
201202 fn && fn();

refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be

lines 203–205why, one step back
203 };
204205 // transfer

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 206–210why, one step back
206 options.path = encodeURIComponent(path);
207 send(this.req, this, next, options);208};209210/**

build `res.download()` on top of `res.sendfile()`Tj Holowaychukbefore adoptiond3ccdbc

lines 211–234why, one step back
211 * Transfer the file at the given `path` as an attachment.
212 *213 * Optionally providing an alternate attachment `filename`,214 * and optional callback `fn(err)`. The callback is invoked215 * when the data transfer is complete, or when an error has216 * ocurred. Be sure to check `res.sendHeader` if you plan to respond.217 *218 * @param {String} path219 * @param {String|Function} filename or fn220 * @param {Function} fn221 * @api public222 */223224res.download = function(path, filename, fn){225 // support function as second arg226 if ('function' == typeof filename) {227 fn = filename;228 filename = null;229 }230231 return this.attachment(filename || path).sendfile(path, fn);232};233234/**

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 235–248why, one step back
235 * Set _Content-Type_ response header passed through `mime.lookup()`.
236 *237 * Examples:238 *239 * var filename = 'path/to/image.png';240 * res.contentType(filename);241 * // res.headers['Content-Type'] is now "image/png"242 *243 * res.contentType('.html');244 * res.contentType('html');245 * res.contentType('json');246 * res.contentType('png');247 *248 * @param {String} type

docsTj Holowaychukbefore adoptionbb9d505

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 250–273why, one step back
250 * @api public
251 */252253res.contentType = function(type){254 return this.header('Content-Type', mime.lookup(type));255};256257/**258 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.259 *260 * @param {String} filename261 * @return {ServerResponse}262 * @api public263 */264265res.attachment = function(filename){266 if (filename) this.contentType(filename);267 this.header('Content-Disposition', filename268 ? 'attachment; filename="' + basename(filename) + '"'269 : 'attachment');270 return this;271};272273/**

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

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

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

line 275why, one step back
275 *

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

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

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

lines 277–281why, one step back
277 * @param {String} val
278 * @return {ServerResponse} for chaining279 * @api public280 */281

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

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

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

lines 284–287why, one step back
284 return this;
285};286287/**

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

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

line 289why, one step back
289 *

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

lines 290–301why, one step back
290 * @param {String} field
291 * @return {String}292 * @api public293 */294295res.get = function(field){296 return this.getHeader(field);297};298299/**300 * Set or get response header `field` with optional `val`.301 *

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 302–303why, one step back
302 * @param {String} name
303 * @param {String} val

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

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 305–307why, one step back
305 * @api public
306 */307

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

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

Refactored `res.header()`Tj Holowaychukbefore adoption54d3751

line 311why, one step back
311 return this;

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 312–318why, one step back
312};
313314/**315 * Clear cookie `name`.316 *317 * @param {String} name318 * @param {Object} options

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

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 320–324why, one step back
320 * @api public
321 */322323res.clearCookie = function(name, options){324 var opts = { expires: new Date(1) };

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

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 326–335why, one step back
326 ? utils.merge(options, opts)
327 : opts);328};329330/**331 * Set cookie `name` to `val`, with the given `options`.332 *333 * Options:334 *335 * - `maxAge` max-age in milliseconds, converted to `expires`

Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 337–354why, one step back
337 *
338 * Examples:339 *340 * // "Remember Me" for 15 minutes341 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });342 *343 * // save as above344 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })345 *346 * @param {String} name347 * @param {String} val348 * @param {Options} options349 * @api public350 */351352res.cookie = function(name, val, options){353 options = options || {};354 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);

Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

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

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

line 358why, one step back
358 return this;

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 359–367why, one step back
359};
360361/**362 * Redirect to the given `url` with optional response `status`363 * defauling to 302.364 *365 * The given `url` can also be the name of a mapped url, for366 * example by default express supports "back" which redirects367 * to the _Referrer_ or _Referer_ headers or the application's

Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 370–407why, one step back
370 *
371 * Redirect Mapping:372 * 373 * To extend the redirect mapping capabilities that Express provides,374 * we may use the `app.redirect()` method:375 * 376 * app.redirect('google', 'http://google.com');377 * 378 * Now in a route we may call:379 *380 * res.redirect('google');381 *382 * We may also map dynamic redirects:383 *384 * app.redirect('comments', function(req, res){385 * return '/post/' + req.params.id + '/comments';386 * });387 *388 * So now we may do the following, and the redirect will dynamically adjust to389 * the context of the request. If we called this route with _GET /post/12_ our390 * redirect _Location_ would be _/post/12/comments_.391 *392 * app.get('/post/:id', function(req, res){393 * res.redirect('comments');394 * });395 *396 * Unless an absolute `url` is given, the app's mount-point397 * will be respected. For example if we redirect to `/posts`,398 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.399 *400 * @param {String} url401 * @param {Number} code402 * @api public403 */404405res.redirect = function(url, status){406 var app = this.app407 , req = this.req

Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b

line 408why, one step back
408 , base = app.set('basepath') || app.route

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 409–431why, one step back
409 , status = status || 302
410 , body;411412 // Setup redirect map413 var map = {414 back: req.header('Referrer', base)415 , home: base416 };417418 // Support custom redirect map419 map.__proto__ = app.redirects;420421 // Attempt mapped redirect422 var mapped = 'function' == typeof map[url]423 ? map[url](req, this)424 : map[url];425426 // Perform redirect427 url = mapped || url;428429 // Relative430 if (!~url.indexOf('://')) {431 // Respect mount-point

Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b

line 432why, one step back
432 if ('/' != base && 0 != url.indexOf(base)) url = base + url;

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 433–441why, one step back
433
434 // Absolute435 var host = req.headers.host436 , tls = req.connection.encrypted;437 url = 'http' + (tls ? 's' : '') + '://' + host + url;438 }439440 // Support text/{plain,html} by default441 if (req.accepts('html')) {

refactored `res.redirect()` slightlyTj Holowaychukbefore adoption6bd5182

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

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

refactored `res.redirect()` slightlyTj Holowaychukbefore adoption6bd5182

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

Release 2.3.7Tj Holowaychukbefore adoption44eae73

lines 446–453why, one step back
446 this.header('Content-Type', 'text/plain');
447 }448449 // Respond450 this.statusCode = status;451 this.header('Location', url);452 this.end(body);453};