Skip to content
Myr

response.js

This file

Path

lib/response.js

450 lines · 10.6 KiB · JavaScript

Last changed by

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

History of this file

Take it

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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.

misc refactoringTj Holowaychukbefore adoption70e6baf

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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 }

misc refactoringTj Holowaychukbefore adoption70e6baf

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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) {

misc refactoringTj Holowaychukbefore adoption70e6baf

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

misc refactoringTj Holowaychukbefore adoption70e6baf

line 145why, one step back
145/**

refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be

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

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

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

refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be

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

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 153–165why, one step back
153 *
154 * Options:155 *156 * - `maxAge` defaulting to 0157 * - `root` root directory for relative filenames158 *159 * @param {String} path160 * @param {Object|Function} options or fn161 * @param {Function} fn162 * @api public163 */164165res.sendfile = function(path, options, fn){

refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be

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

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

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

refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be

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

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 170–176why, one step back
170
171 // support function as second arg172 if ('function' == typeof options) {173 fn = options;174 options = {};175 }176

refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be

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

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

lines 180–186why, one step back
180 self.sentHeader = !! self._header;
181182 // error183 if (err) {184 // ditch content-disposition to prevent funky responses185 if (!self.sentHeader) self.removeHeader('Content-Disposition');186

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

lines 187–189why, one step back
187 // not found
188 if ('ENOENT' == err.code) return req.next();189

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

lines 190–195why, one step back
190 // lost in limbo if there's no callback
191 if (self.sentHeader) return fn && fn(err);192193 // callback available194 if (fn) return fn(err);195

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

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

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

lines 197–199why, one step back
197 }
198199 fn && fn();

refactored `res.sendfile()`Tj Holowaychukbefore adoption5da28be

lines 200–202why, one step back
200 };
201202 // transfer

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 203–207why, one step back
203 options.path = encodeURIComponent(path);
204 send(this.req, this, next, options);205};206207/**

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

lines 208–231why, one step back
208 * Transfer the file at the given `path` as an attachment.
209 *210 * Optionally providing an alternate attachment `filename`,211 * and optional callback `fn(err)`. The callback is invoked212 * when the data transfer is complete, or when an error has213 * ocurred. Be sure to check `res.sendHeader` if you plan to respond.214 *215 * @param {String} path216 * @param {String|Function} filename or fn217 * @param {Function} fn218 * @api public219 */220221res.download = function(path, filename, fn){222 // support function as second arg223 if ('function' == typeof filename) {224 fn = filename;225 filename = null;226 }227228 return this.attachment(filename || path).sendfile(path, fn);229};230231/**

misc refactoringTj Holowaychukbefore adoption70e6baf

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

docsTj Holowaychukbefore adoptionbb9d505

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

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 247–270why, one step back
247 * @api public
248 */249250res.contentType = function(type){251 return this.header('Content-Type', mime.lookup(type));252};253254/**255 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.256 *257 * @param {String} filename258 * @return {ServerResponse}259 * @api public260 */261262res.attachment = function(filename){263 if (filename) this.contentType(filename);264 this.header('Content-Disposition', filename265 ? 'attachment; filename="' + basename(filename) + '"'266 : 'attachment');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 * Set header `field` to `val`.

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

line 272why, one step back
272 *

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

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

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

lines 274–278why, one step back
274 * @param {String} val
275 * @return {ServerResponse} for chaining276 * @api public277 */278

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

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

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

lines 281–284why, one step back
281 return this;
282};283284/**

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

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

misc refactoringTj Holowaychukbefore adoption70e6baf

line 286why, one step back
286 *

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

lines 287–298why, one step back
287 * @param {String} field
288 * @return {String}289 * @api public290 */291292res.get = function(field){293 return this.getHeader(field);294};295296/**297 * Set or get response header `field` with optional `val`.298 *

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 299–300why, one step back
299 * @param {String} name
300 * @param {String} val

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

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

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 302–304why, one step back
302 * @api public
303 */304

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

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

Refactored `res.header()`Tj Holowaychukbefore adoption54d3751

line 308why, one step back
308 return this;

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 309–315why, one step back
309};
310311/**312 * Clear cookie `name`.313 *314 * @param {String} name315 * @param {Object} options

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

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

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

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

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 323–332why, one step back
323 ? utils.merge(options, opts)
324 : opts);325};326327/**328 * Set cookie `name` to `val`, with the given `options`.329 *330 * Options:331 *332 * - `maxAge` max-age in milliseconds, converted to `expires`

Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b

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

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 334–351why, one step back
334 *
335 * Examples:336 *337 * // "Remember Me" for 15 minutes338 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });339 *340 * // save as above341 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })342 *343 * @param {String} name344 * @param {String} val345 * @param {Options} options346 * @api public347 */348349res.cookie = function(name, val, options){350 options = options || {};351 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);

Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

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

line 355why, one step back
355 return this;

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 356–364why, one step back
356};
357358/**359 * Redirect to the given `url` with optional response `status`360 * defauling to 302.361 *362 * The given `url` can also be the name of a mapped url, for363 * example by default express supports "back" which redirects364 * to the _Referrer_ or _Referer_ headers or the application's

Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b

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

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 406–428why, one step back
406 , status = status || 302
407 , body;408409 // Setup redirect map410 var map = {411 back: req.header('Referrer', base)412 , home: base413 };414415 // Support custom redirect map416 map.__proto__ = app.redirects;417418 // Attempt mapped redirect419 var mapped = 'function' == typeof map[url]420 ? map[url](req, this)421 : map[url];422423 // Perform redirect424 url = mapped || url;425426 // Relative427 if (!~url.indexOf('://')) {428 // Respect mount-point

Merged basepath setting. Closes #813Tj Holowaychukbefore adoptione9abe1b

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

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 430–438why, one step back
430
431 // Absolute432 var host = req.headers.host433 , tls = req.connection.encrypted;434 url = 'http' + (tls ? 's' : '') + '://' + host + url;435 }436437 // Support text/{plain,html} by default438 if (req.accepts('html')) {

refactored `res.redirect()` slightlyTj Holowaychukbefore adoption6bd5182

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

misc refactoringTj Holowaychukbefore adoption70e6baf

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

refactored `res.redirect()` slightlyTj Holowaychukbefore adoption6bd5182

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

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 443–450why, one step back
443 this.header('Content-Type', 'text/plain');
444 }445446 // Respond447 this.statusCode = status;448 this.header('Location', url);449 this.end(body);450};