Skip to content
Myr

response.js

This file

Path

lib/response.js

641 lines · 14.7 KiB · JavaScript

Last changed by

update headersTJ Holowaychukbefore adoptiona376980

History of this file

Take it

The walk stopped after 200 commits: lines older than 0f72ca8 point at it.

docsTj Holowaychukbefore adoption0f72ca8

lines 1–3why, one step back
1
2/*!3 * Express - response

update headersTJ Holowaychukbefore adoptiona376980

line 4why, one step back
4 * Copyright(c) 2010-2012 TJ Holowaychuk <tj@vision-media.ca>

docsTj Holowaychukbefore adoption0f72ca8

lines 5–16why, one step back
5 * MIT Licensed
6 */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

Added array support. Closes #1053TJ Holowaychukbefore adoption298899d

lines 17–18why, one step back
17 , normalizeType = require('./utils').normalizeType
18 , normalizeTypes = require('./utils').normalizeTypes

docsTj Holowaychukbefore adoption0f72ca8

lines 19–22why, one step back
19 , statusCodes = http.STATUS_CODES
20 , send = connect.static.send21 , mime = require('mime')22 , basename = path.basename

Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95

line 23why, one step back
23 , extname = path.extname

docsTj Holowaychukbefore adoption0f72ca8

lines 24–72why, one step back
24 , join = path.join;
2526/**27 * Response prototype.28 */2930var res = module.exports = {31 __proto__: http.ServerResponse.prototype32};3334/**35 * Set status `code`.36 *37 * @param {Number} code38 * @return {ServerResponse}39 * @api public40 */4142res.status = function(code){43 this.statusCode = code;44 return this;45};4647/**48 * Send a response.49 *50 * Examples:51 *52 * res.send(new Buffer('wahoo'));53 * res.send({ some: 'json' });54 * res.send('<p>some html</p>');55 * res.send(404, 'Sorry, cant find that');56 * res.send(404);57 *58 * @param {Mixed} body or status59 * @param {Mixed} body60 * @return {ServerResponse}61 * @api public62 */6364res.send = function(body){65 var req = this.req66 , head = 'HEAD' == req.method;6768 // allow status / body69 if (2 == arguments.length) {70 this.statusCode = body;71 body = arguments[1];72 }

Merge pull request #1100 from coolony/masterTJ Holowaychukbefore adoption1ddf0c8

line 73why, one step back
73

refactored res.send()TJ Holowaychukbefore adoptionb809041

lines 74–75why, one step back
74 // convert string objects to primitives
75 if (body instanceof String) body = body.toString();

docsTj Holowaychukbefore adoption0f72ca8

lines 76–79why, one step back
76
77 switch (typeof body) {78 // response status79 case 'number':

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 80why, one step back
80 this.get('Content-Type') || this.contentType('.txt');

docsTj Holowaychukbefore adoption0f72ca8

lines 81–85why, one step back
81 this.statusCode = body;
82 body = http.STATUS_CODES[body];83 break;84 // string defaulting to html85 case 'string':

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 86why, one step back
86 if (!this.get('Content-Type')) {

docsTj Holowaychukbefore adoption0f72ca8

lines 87–95why, one step back
87 this.charset = this.charset || 'utf-8';
88 this.contentType('.html');89 }90 break;91 case 'boolean':92 case 'object':93 if (null == body) {94 body = '';95 } else if (Buffer.isBuffer(body)) {

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

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

docsTj Holowaychukbefore adoption0f72ca8

lines 97–103why, one step back
97 } else {
98 return this.json(body);99 }100 break;101 }102103 // populate Content-Length

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

lines 104–105why, one step back
104 if (undefined !== body && !this.get('Content-Length')) {
105 this.set('Content-Length', Buffer.isBuffer(body)

docsTj Holowaychukbefore adoption0f72ca8

lines 106–144why, one step back
106 ? body.length
107 : Buffer.byteLength(body));108 }109110 // strip irrelevant headers111 if (204 == this.statusCode || 304 == this.statusCode) {112 this.removeHeader('Content-Type');113 this.removeHeader('Content-Length');114 body = '';115 }116117 // respond118 this.end(head ? null : body);119 return this;120};121122/**123 * Send JSON response.124 *125 * Examples:126 *127 * res.json(null);128 * res.json({ user: 'tj' });129 * res.json(500, 'oh noes!');130 * res.json(404, 'I dont have that');131 *132 * @param {Mixed} obj or status133 * @param {Mixed} obj134 * @return {ServerResponse}135 * @api public136 */137138res.json = function(obj){139 // allow status / body140 if (2 == arguments.length) {141 this.statusCode = obj;142 obj = arguments[1];143 }144

Fixed: use app.get() for all core settingsTJ Holowaychukbefore adoption8f87400

lines 145–148why, one step back
145 var app = this.app
146 , jsonp = app.get('jsonp callback')147 , replacer = app.get('json replacer')148 , spaces = app.get('json spaces')

Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa

lines 149–150why, one step back
149 , body = JSON.stringify(obj, replacer, spaces)
150 , callback = this.req.query.callback;

docsTj Holowaychukbefore adoption0f72ca8

lines 151–152why, one step back
151
152 this.charset = this.charset || 'utf-8';

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 153why, one step back
153 this.set('Content-Type', 'application/json');

docsTj Holowaychukbefore adoption0f72ca8

lines 154–155why, one step back
154
155 if (callback && jsonp) {

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 156why, one step back
156 this.set('Content-Type', 'text/javascript');

docsTj Holowaychukbefore adoption0f72ca8

lines 157–176why, one step back
157 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';
158 }159160 return this.send(body);161};162163/**164 * Transfer the file at the given `path`.165 * 166 * Automatically sets the _Content-Type_ response header field.167 * The callback `fn(err)` is invoked when the transfer is complete168 * or when an error occurs. Be sure to check `res.sentHeader`169 * if you wish to attempt responding, as the header and some data170 * may have already been transferred.171 *172 * Options:173 *174 * - `maxAge` defaulting to 0175 * - `root` root directory for relative filenames176 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 177–196why, one step back
177 * Examples:
178 *179 * The following example illustrates how `res.sendfile()` may180 * be used as an alternative for the `static()` middleware for181 * dynamic situations. The code backing `res.sendfile()` is actually182 * the same code, so HTTP cache support etc is identical.183 *184 * app.get('/user/:uid/photos/:file', function(req, res){185 * var uid = req.params.uid186 * , file = req.params.file;187 * 188 * req.user.mayViewFilesFrom(uid, function(yes){189 * if (yes) {190 * res.sendfile('/uploads/' + uid + '/' + file);191 * } else {192 * res.send(403, 'Sorry! you cant see that.');193 * }194 * });195 * });196 *

docsTj Holowaychukbefore adoption0f72ca8

lines 197–218why, one step back
197 * @param {String} path
198 * @param {Object|Function} options or fn199 * @param {Function} fn200 * @api public201 */202203res.sendfile = function(path, options, fn){204 var self = this205 , req = self.req206 , next = this.req.next207 , options = options || {};208209 // support function as second arg210 if ('function' == typeof options) {211 fn = options;212 options = {};213 }214215 // callback216 options.callback = function(err){217 if (err) {218 // cast ENOENT

refactored res.sendfile()TJ Holowaychukbefore adoptioncf7d710

line 219why, one step back
219 if ('ENOENT' == err.code) err = utils.error(404);

docsTj Holowaychukbefore adoption0f72ca8

lines 220–248why, one step back
220
221 // ditch content-disposition to prevent funky responses222 if (!self.headerSent) self.removeHeader('Content-Disposition');223224 // woot! callback available225 if (fn) return fn(err);226227 // lost in limbo if there's no callback228 if (self.headerSent) return;229230 return req.next(err);231 }232233 fn && fn();234 };235236 // transfer237 options.path = encodeURIComponent(path);238 send(this.req, this, next, options);239};240241/**242 * Transfer the file at the given `path` as an attachment.243 *244 * Optionally providing an alternate attachment `filename`,245 * and optional callback `fn(err)`. The callback is invoked246 * when the data transfer is complete, or when an error has247 * ocurred. Be sure to check `res.headerSent` if you plan to respond.248 *

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

lines 249–250why, one step back
249 * This method uses `res.attachment()` and `res.sendfile()`.
250 *

docsTj Holowaychukbefore adoption0f72ca8

lines 251–267why, one step back
251 * @param {String} path
252 * @param {String|Function} filename or fn253 * @param {Function} fn254 * @api public255 */256257res.download = function(path, filename, fn){258 // support function as second arg259 if ('function' == typeof filename) {260 fn = filename;261 filename = null;262 }263264 return this.attachment(filename || path).sendfile(path, fn);265};266267/**

Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95

lines 268–269why, one step back
268 * Set _Content-Type_ response header with `type` through `mime.lookup()`
269 * when it does not contain "/", or set the Content-Type to `type` otherwise.

docsTj Holowaychukbefore adoption0f72ca8

lines 270–272why, one step back
270 *
271 * Examples:272 *

Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95

lines 273–276why, one step back
273 * res.type('.html');
274 * res.type('html');275 * res.type('json');276 * res.type('application/json');

docsTj Holowaychukbefore adoption0f72ca8

lines 277–285why, one step back
277 * res.type('png');
278 *279 * @param {String} type280 * @return {ServerResponse} for chaining281 * @api public282 */283284res.contentType =285res.type = function(type){

Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95

lines 286–288why, one step back
286 return this.set('Content-Type', ~type.indexOf('/')
287 ? type288 : mime.lookup(type));

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

lines 289–301why, one step back
289};
290291/**292 * Respond to the Acceptable formats using an `obj`293 * of mime-type callbacks.294 *295 * This method uses `req.accepted`, an array of296 * acceptable types ordered by their quality values.297 * When "Accept" is not present the _first_ callback298 * is invoked, otherwise the first match is used. When299 * no match is performed the server responds with300 * 406 "Not Acceptable".301 *

Added extname support to `res.format()`. Closes #1024TJ Holowaychukbefore adoptioneb3105e

lines 302–304why, one step back
302 * Content-Type is set for you, however if you choose
303 * you may alter this within the callback using `res.type()`304 * or `res.set('Content-Type', ...)`.

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

line 305why, one step back
305 *

renamed `res.respondTo()` to `res.format()`TJ Holowaychukbefore adoptionffcaa04

line 306why, one step back
306 * res.format({

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

line 307why, one step back
307 * 'text/plain': function(){

Added extname support to `res.format()`. Closes #1024TJ Holowaychukbefore adoptioneb3105e

line 308why, one step back
308 * res.send('hey');

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

lines 309–319why, one step back
309 * },
310 * 311 * 'text/html': function(){312 * res.send('<p>hey</p>');313 * },314 * 315 * 'appliation/json': function(){316 * res.send({ message: 'hey' });317 * }318 * });319 *

Added extname support to `res.format()`. Closes #1024TJ Holowaychukbefore adoptioneb3105e

lines 320–336why, one step back
320 * In addition to canonicalized MIME types you may
321 * also use extnames mapped to these types:322 *323 * res.format({324 * text: function(){325 * res.send('hey');326 * },327 * 328 * html: function(){329 * res.send('<p>hey</p>');330 * },331 * 332 * json: function(){333 * res.send({ message: 'hey' });334 * }335 * });336 *

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

lines 337–341why, one step back
337 * @param {Object} obj
338 * @return {ServerResponse} for chaining339 * @api public340 */341

renamed `res.respondTo()` to `res.format()`TJ Holowaychukbefore adoptionffcaa04

line 342why, one step back
342res.format = function(obj){

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

lines 343–345why, one step back
343 var keys = Object.keys(obj)
344 , req = this.req345 , next = req.next

Added array support. Closes #1053TJ Holowaychukbefore adoption298899d

line 346why, one step back
346 , key = req.accepts(keys);

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

line 347why, one step back
347

Added: `res.format()` sets Vary: AcceptTJ Holowaychukbefore adoption12e0878

lines 348–349why, one step back
348 this.set('Vary', 'Accept');
349

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

line 350why, one step back
350 if (key) {

Added array support. Closes #1053TJ Holowaychukbefore adoption298899d

line 351why, one step back
351 this.set('Content-Type', normalizeType(key));

Added: `res.respondTo()` defaults the content-typeTJ Holowaychukbefore adoptionbdfa6d1

line 352why, one step back
352 obj[key](req, this, next);

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

lines 353–355why, one step back
353 } else {
354 var err = new Error('Not Acceptable');355 err.status = 406;

Added array support. Closes #1053TJ Holowaychukbefore adoption298899d

line 356why, one step back
356 err.types = normalizeTypes(keys);

Added `res.respondTo(obj)`TJ Holowaychukbefore adoptionb565e25

lines 357–360why, one step back
357 next(err);
358 }359360 return this;

docsTj Holowaychukbefore adoption0f72ca8

lines 361–371why, one step back
361};
362363/**364 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.365 *366 * @param {String} filename367 * @return {ServerResponse}368 * @api public369 */370371res.attachment = function(filename){

Changed to allow extname or type/subtype only. Closes #1072TJ Holowaychukbefore adoption24a4e95

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

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 373why, one step back
373 this.set('Content-Disposition', filename

docsTj Holowaychukbefore adoption0f72ca8

lines 374–387why, one step back
374 ? 'attachment; filename="' + basename(filename) + '"'
375 : 'attachment');376 return this;377};378379/**380 * Set header `field` to `val`, or pass381 * an object of of header fields.382 *383 * Examples:384 *385 * res.set('Accept', 'application/json');386 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });387 *

docsTJ Holowaychukbefore adoption27b1b5e

lines 388–389why, one step back
388 * Aliased as `res.header()`.
389 *

docsTj Holowaychukbefore adoption0f72ca8

lines 390–395why, one step back
390 * @param {String|Object} field
391 * @param {String} val392 * @return {ServerResponse} for chaining393 * @api public394 */395

Added `res.header()` and `req.header()` aliases for BCTJ Holowaychukbefore adoption5fa2f89

lines 396–397why, one step back
396res.set =
397res.header = function(field, val){

docsTj Holowaychukbefore adoption0f72ca8

lines 398–479why, one step back
398 if (2 == arguments.length) {
399 this.setHeader(field, val);400 } else {401 for (var key in field) {402 this.setHeader(key, field[key]);403 }404 }405 return this;406};407408/**409 * Get value for header `field`.410 *411 * @param {String} field412 * @return {String}413 * @api public414 */415416res.get = function(field){417 return this.getHeader(field);418};419420/**421 * Clear cookie `name`.422 *423 * @param {String} name424 * @param {Object} options425 * @param {ServerResponse} for chaining426 * @api public427 */428429res.clearCookie = function(name, options){430 var opts = { expires: new Date(1), path: '/' };431 return this.cookie(name, '', options432 ? utils.merge(opts, options)433 : opts);434};435436/**437 * Set a signed cookie with the given `name` and `val`.438 * See `res.cookie()` for details.439 *440 * @param {String} name441 * @param {String|Object} val442 * @param {Object} options443 * @api public444 */445446res.signedCookie = function(name, val, options){447 var secret = this.req.secret;448 if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');449 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);450 val = utils.sign(val, secret);451 return this.cookie(name, val, options);452};453454/**455 * Set cookie `name` to `val`, with the given `options`.456 *457 * Options:458 *459 * - `maxAge` max-age in milliseconds, converted to `expires`460 * - `path` defaults to "/"461 *462 * Examples:463 *464 * // "Remember Me" for 15 minutes465 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });466 *467 * // save as above468 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })469 *470 * @param {String} name471 * @param {String|Object} val472 * @param {Options} options473 * @api public474 */475476res.cookie = function(name, val, options){477 options = options || {};478 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);479 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption85ea5f6

line 480why, one step back
480 if (null == options.path) options.path = '/';

docsTj Holowaychukbefore adoption0f72ca8

line 481why, one step back
481 var cookie = utils.serializeCookie(name, val, options);

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 482why, one step back
482 this.set('Set-Cookie', cookie);

docsTj Holowaychukbefore adoption0f72ca8

lines 483–498why, one step back
483 return this;
484};485486/**487 * Redirect to the given `url` with optional response `status`488 * defaulting to 302.489 *490 * The given `url` can also be the name of a mapped url, for491 * example by default express supports "back" which redirects492 * to the _Referrer_ or _Referer_ headers or "/".493 *494 * Examples:495 *496 * res.redirect('/foo/bar');497 * res.redirect('http://example.com');498 * res.redirect(301, 'http://example.com');

added another res.redirect() exampleTJ Holowaychukbefore adoptionba413ee

line 499why, one step back
499 * res.redirect('../login'); // /blog/post/1 -> /blog/login

docsTj Holowaychukbefore adoption0f72ca8

lines 500–532why, one step back
500 *
501 * Mounting:502 *503 * When an application is mounted, and `res.redirect()`504 * is given a path that does _not_ lead with "/". For 505 * example suppose a "blog" app is mounted at "/blog",506 * the following redirect would result in "/blog/login":507 *508 * res.redirect('login');509 *510 * While the leading slash would result in a redirect to "/login":511 *512 * res.redirect('/login');513 *514 * @param {String} url515 * @param {Number} code516 * @api public517 */518519res.redirect = function(url){520 var app = this.app521 , req = this.req522 , head = 'HEAD' == req.method523 , status = 302524 , body;525526 // allow status / url527 if (2 == arguments.length) {528 status = url;529 url = arguments[1];530 }531532 // setup redirect map

Removed `res.header(field, value)`TJ Holowaychukbefore adoption76fd462

line 533why, one step back
533 var map = { back: req.get('Referrer') || '/' };

docsTj Holowaychukbefore adoption0f72ca8

lines 534–535why, one step back
534
535 // perform redirect

Removed `app.redirect()`Tj Holowaychukbefore adoption4329528

line 536why, one step back
536 url = map[url] || url;

docsTj Holowaychukbefore adoption0f72ca8

lines 537–541why, one step back
537
538 // relative539 if (!~url.indexOf('://')) {540 var path = app.path();541

Added support for ./ in redirectsTj Holowaychukbefore adoption489265e

line 542why, one step back
542 // relative to path

Added support for .. in redirects as wellTj Holowaychukbefore adoption88f154f

lines 543–544why, one step back
543 if (0 == url.indexOf('./') || 0 == url.indexOf('..')) {
544 url = req.path + '/' + url;

docsTj Holowaychukbefore adoption0f72ca8

line 545why, one step back
545 // relative to mount-point

Added support for ./ in redirectsTj Holowaychukbefore adoption489265e

line 546why, one step back
546 } else if ('/' != url[0]) {

docsTj Holowaychukbefore adoption0f72ca8

lines 547–550why, one step back
547 url = path + '/' + url;
548 }549550 // Absolute

Removed `res.header(field, value)`TJ Holowaychukbefore adoption76fd462

line 551why, one step back
551 var host = req.get('Host');

Added "trust proxy" settingTJ Holowaychukbefore adoption4d87efc

line 552why, one step back
552 url = req.protocol + '://' + host + url;

docsTj Holowaychukbefore adoption0f72ca8

lines 553–555why, one step back
553 }
554555 // Support text/{plain,html} by default

renamed `res.respondTo()` to `res.format()`TJ Holowaychukbefore adoptionffcaa04

line 556why, one step back
556 this.format({

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 557why, one step back
557 text: function(){

refactored res.redirect() with respondTo()TJ Holowaychukbefore adoptiona47660b

lines 558–560why, one step back
558 body = statusCodes[status] + '. Redirecting to ' + url;
559 },560

Added new dox API docsTJ Holowaychukbefore adoption7e81cad

line 561why, one step back
561 html: function(){

refactored res.redirect() with respondTo()TJ Holowaychukbefore adoptiona47660b

lines 562–564why, one step back
562 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';
563 }564 })

docsTj Holowaychukbefore adoption0f72ca8

lines 565–567why, one step back
565
566 // Respond567 this.statusCode = status;

utilize `res.set()` internallyTJ Holowaychukbefore adoptionc44f018

line 568why, one step back
568 this.set('Location', url);

docsTj Holowaychukbefore adoption0f72ca8

lines 569–641why, one step back
569 this.end(head ? null : body);
570};571572/**573 * Render `view` with the given `options` and optional callback `fn`.574 * When a callback function is given a response will _not_ be made575 * automatically, otherwise a response of _200_ and _text/html_ is given.576 *577 * Options:578 * 579 * - `status` Response status code (`res.statusCode`)580 * - `charset` Set the charset (`res.charset`)581 *582 * Reserved locals:583 *584 * - `cache` boolean hinting to the engine it should cache585 * - `filename` filename of the view being rendered586 *587 * @param {String} view588 * @param {Object|Function} options or callback function589 * @param {Function} fn590 * @api public591 */592593res.render = function(view, options, fn){594 var self = this595 , options = options || {}596 , req = this.req597 , app = req.app;598599 // support callback function as second arg600 if ('function' == typeof options) {601 fn = options, options = {};602 }603604 function render() {605 // merge res.locals606 options.locals = self.locals;607608 // default callback to respond609 fn = fn || function(err, str){610 if (err) return req.next(err);611 self.send(str);612 };613614 // render615 app.render(view, options, fn);616 }617618 // invoke view callbacks619 var callbacks = app.viewCallbacks620 , pending = callbacks.length621 , len = pending622 , done;623624 if (len) {625 for (var i = 0; i < len; ++i) {626 callbacks[i](req, self, function(err){627 if (done) return;628629 if (err) {630 req.next(err);631 done = true;632 return;633 }634635 --pending || render();636 });637 }638 } else {639 render();640 }641};