response.js
This file
Path
lib/response.js
643 lines · 14.7 KiB · JavaScript
Last changed by
docsTJ Holowaychukbefore adoption27b1b5e
History of this fileTake it
12/*!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 , normalizeType = require('./utils').normalizeType18 , normalizeTypes = require('./utils').normalizeTypes19 , statusCodes = http.STATUS_CODES20 , send = connect.static.send21 , mime = require('mime')22 , basename = path.basename23 , extname = path.extname24 , 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 }7374 switch (typeof body) {75 // response status76 case 'number':77 this.get('Content-Type') || this.contentType('.txt');78 this.statusCode = body;79 body = http.STATUS_CODES[body];80 break;81 // string defaulting to html82 case 'string':83 if (!this.get('Content-Type')) {84 this.charset = this.charset || 'utf-8';85 this.contentType('.html');86 }87 break;88 case 'boolean':89 case 'object':90 if (null == body) {91 body = '';92 } else if (Buffer.isBuffer(body)) {93 this.get('Content-Type') || this.contentType('.bin');94 } else {95 return this.json(body);96 }97 break;98 }99100 // populate Content-Length101 if (undefined !== body && !this.get('Content-Length')) {102 this.set('Content-Length', Buffer.isBuffer(body)103 ? body.length104 : Buffer.byteLength(body));105 }106107 // strip irrelevant headers108 if (204 == this.statusCode || 304 == this.statusCode) {109 this.removeHeader('Content-Type');110 this.removeHeader('Content-Length');111 body = '';112 }113114 // respond115 this.end(head ? null : body);116 return this;117};118119/**120 * Send JSON response.121 *122 * Examples:123 *124 * res.json(null);125 * res.json({ user: 'tj' });126 * res.json(500, 'oh noes!');127 * res.json(404, 'I dont have that');128 *129 * @param {Mixed} obj or status130 * @param {Mixed} obj131 * @return {ServerResponse}132 * @api public133 */134135res.json = function(obj){136 // allow status / body137 if (2 == arguments.length) {138 this.statusCode = obj;139 obj = arguments[1];140 }141142 var settings = this.app.settings143 , jsonp = settings['jsonp callback']144 , replacer = settings['json replacer']145 , spaces = settings['json spaces']146 , body = JSON.stringify(obj, replacer, spaces)147 , callback = this.req.query.callback;148149 this.charset = this.charset || 'utf-8';150 this.set('Content-Type', 'application/json');151152 if (callback && jsonp) {153 this.set('Content-Type', 'text/javascript');154 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';155 }156157 return this.send(body);158};159160/**161 * Transfer the file at the given `path`.162 * 163 * Automatically sets the _Content-Type_ response header field.164 * The callback `fn(err)` is invoked when the transfer is complete165 * or when an error occurs. Be sure to check `res.sentHeader`166 * if you wish to attempt responding, as the header and some data167 * may have already been transferred.168 *169 * Options:170 *171 * - `maxAge` defaulting to 0172 * - `root` root directory for relative filenames173 *174 * Examples:175 *176 * The following example illustrates how `res.sendfile()` may177 * be used as an alternative for the `static()` middleware for178 * dynamic situations. The code backing `res.sendfile()` is actually179 * the same code, so HTTP cache support etc is identical.180 *181 * app.get('/user/:uid/photos/:file', function(req, res){182 * var uid = req.params.uid183 * , file = req.params.file;184 * 185 * req.user.mayViewFilesFrom(uid, function(yes){186 * if (yes) {187 * res.sendfile('/uploads/' + uid + '/' + file);188 * } else {189 * res.send(403, 'Sorry! you cant see that.');190 * }191 * });192 * });193 *194 * @param {String} path195 * @param {Object|Function} options or fn196 * @param {Function} fn197 * @api public198 */199200res.sendfile = function(path, options, fn){201 var self = this202 , req = self.req203 , next = this.req.next204 , options = options || {};205206 // support function as second arg207 if ('function' == typeof options) {208 fn = options;209 options = {};210 }211212 // callback213 options.callback = function(err){214 if (err) {215 // cast ENOENT216 if ('ENOENT' == err.code) err = 404;217218 // coerce numeric error to an Error219 // TODO: remove220 // TODO: remove docs for headerSent?221 if ('number' == typeof err) err = utils.error(err);222223 // ditch content-disposition to prevent funky responses224 if (!self.headerSent) self.removeHeader('Content-Disposition');225226 // woot! callback available227 if (fn) return fn(err);228229 // lost in limbo if there's no callback230 if (self.headerSent) return;231232 return req.next(err);233 }234235 fn && fn();236 };237238 // transfer239 options.path = encodeURIComponent(path);240 send(this.req, this, next, options);241};242243/**244 * Transfer the file at the given `path` as an attachment.245 *246 * Optionally providing an alternate attachment `filename`,247 * and optional callback `fn(err)`. The callback is invoked248 * when the data transfer is complete, or when an error has249 * ocurred. Be sure to check `res.headerSent` if you plan to respond.250 *251 * This method uses `res.attachment()` and `res.sendfile()`.252 *253 * @param {String} path254 * @param {String|Function} filename or fn255 * @param {Function} fn256 * @api public257 */258259res.download = function(path, filename, fn){260 // support function as second arg261 if ('function' == typeof filename) {262 fn = filename;263 filename = null;264 }265266 return this.attachment(filename || path).sendfile(path, fn);267};268269/**270 * Set _Content-Type_ response header with `type` through `mime.lookup()`271 * when it does not contain "/", or set the Content-Type to `type` otherwise.272 *273 * Examples:274 *275 * res.type('.html');276 * res.type('html');277 * res.type('json');278 * res.type('application/json');279 * res.type('png');280 *281 * @param {String} type282 * @return {ServerResponse} for chaining283 * @api public284 */285286res.contentType =287res.type = function(type){288 return this.set('Content-Type', ~type.indexOf('/')289 ? type290 : mime.lookup(type));291};292293/**294 * Respond to the Acceptable formats using an `obj`295 * of mime-type callbacks.296 *297 * This method uses `req.accepted`, an array of298 * acceptable types ordered by their quality values.299 * When "Accept" is not present the _first_ callback300 * is invoked, otherwise the first match is used. When301 * no match is performed the server responds with302 * 406 "Not Acceptable".303 *304 * Content-Type is set for you, however if you choose305 * you may alter this within the callback using `res.type()`306 * or `res.set('Content-Type', ...)`.307 *308 * res.format({309 * 'text/plain': function(){310 * res.send('hey');311 * },312 * 313 * 'text/html': function(){314 * res.send('<p>hey</p>');315 * },316 * 317 * 'appliation/json': function(){318 * res.send({ message: 'hey' });319 * }320 * });321 *322 * In addition to canonicalized MIME types you may323 * also use extnames mapped to these types:324 *325 * res.format({326 * text: function(){327 * res.send('hey');328 * },329 * 330 * html: function(){331 * res.send('<p>hey</p>');332 * },333 * 334 * json: function(){335 * res.send({ message: 'hey' });336 * }337 * });338 *339 * @param {Object} obj340 * @return {ServerResponse} for chaining341 * @api public342 */343344res.format = function(obj){345 var keys = Object.keys(obj)346 , req = this.req347 , next = req.next348 , key = req.accepts(keys);349350 this.set('Vary', 'Accept');351352 if (key) {353 this.set('Content-Type', normalizeType(key));354 obj[key](req, this, next);355 } else {356 var err = new Error('Not Acceptable');357 err.status = 406;358 err.types = normalizeTypes(keys);359 next(err);360 }361362 return this;363};364365/**366 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.367 *368 * @param {String} filename369 * @return {ServerResponse}370 * @api public371 */372373res.attachment = function(filename){374 if (filename) this.type(extname(filename));375 this.set('Content-Disposition', filename376 ? 'attachment; filename="' + basename(filename) + '"'377 : 'attachment');378 return this;379};380381/**382 * Set header `field` to `val`, or pass383 * an object of of header fields.384 *385 * Examples:386 *387 * res.set('Accept', 'application/json');388 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });389 *390 * Aliased as `res.header()`. 391 *392 * @param {String|Object} field393 * @param {String} val394 * @return {ServerResponse} for chaining395 * @api public396 */397398res.set = 399res.header = function(field, val){400 if (2 == arguments.length) {401 this.setHeader(field, val);402 } else {403 for (var key in field) {404 this.setHeader(key, field[key]);405 }406 }407 return this;408};409410/**411 * Get value for header `field`.412 *413 * @param {String} field414 * @return {String}415 * @api public416 */417418res.get = function(field){419 return this.getHeader(field);420};421422/**423 * Clear cookie `name`.424 *425 * @param {String} name426 * @param {Object} options427 * @param {ServerResponse} for chaining428 * @api public429 */430431res.clearCookie = function(name, options){432 var opts = { expires: new Date(1), path: '/' };433 return this.cookie(name, '', options434 ? utils.merge(opts, options)435 : opts);436};437438/**439 * Set a signed cookie with the given `name` and `val`.440 * See `res.cookie()` for details.441 *442 * @param {String} name443 * @param {String|Object} val444 * @param {Object} options445 * @api public446 */447448res.signedCookie = function(name, val, options){449 var secret = this.req.secret;450 if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');451 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);452 val = utils.sign(val, secret);453 return this.cookie(name, val, options);454};455456/**457 * Set cookie `name` to `val`, with the given `options`.458 *459 * Options:460 *461 * - `maxAge` max-age in milliseconds, converted to `expires`462 * - `path` defaults to "/"463 *464 * Examples:465 *466 * // "Remember Me" for 15 minutes467 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });468 *469 * // save as above470 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })471 *472 * @param {String} name473 * @param {String|Object} val474 * @param {Options} options475 * @api public476 */477478res.cookie = function(name, val, options){479 options = options || {};480 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);481 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);482 if (null == options.path) options.path = '/';483 var cookie = utils.serializeCookie(name, val, options);484 this.set('Set-Cookie', cookie);485 return this;486};487488/**489 * Redirect to the given `url` with optional response `status`490 * defaulting to 302.491 *492 * The given `url` can also be the name of a mapped url, for493 * example by default express supports "back" which redirects494 * to the _Referrer_ or _Referer_ headers or "/".495 *496 * Examples:497 *498 * res.redirect('/foo/bar');499 * res.redirect('http://example.com');500 * res.redirect(301, 'http://example.com');501 * res.redirect('../login'); // /blog/post/1 -> /blog/login502 *503 * Mounting:504 *505 * When an application is mounted, and `res.redirect()`506 * is given a path that does _not_ lead with "/". For 507 * example suppose a "blog" app is mounted at "/blog",508 * the following redirect would result in "/blog/login":509 *510 * res.redirect('login');511 *512 * While the leading slash would result in a redirect to "/login":513 *514 * res.redirect('/login');515 *516 * @param {String} url517 * @param {Number} code518 * @api public519 */520521res.redirect = function(url){522 var app = this.app523 , req = this.req524 , head = 'HEAD' == req.method525 , status = 302526 , body;527528 // allow status / url529 if (2 == arguments.length) {530 status = url;531 url = arguments[1];532 }533534 // setup redirect map535 var map = { back: req.get('Referrer') || '/' };536537 // perform redirect538 url = map[url] || url;539540 // relative541 if (!~url.indexOf('://')) {542 var path = app.path();543544 // relative to path545 if (0 == url.indexOf('./') || 0 == url.indexOf('..')) {546 url = req.path + '/' + url;547 // relative to mount-point548 } else if ('/' != url[0]) {549 url = path + '/' + url;550 }551552 // Absolute553 var host = req.get('Host');554 url = req.protocol + '://' + host + url;555 }556557 // Support text/{plain,html} by default558 this.format({559 text: function(){560 body = statusCodes[status] + '. Redirecting to ' + url;561 },562563 html: function(){564 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';565 }566 })567568 // Respond569 this.statusCode = status;570 this.set('Location', url);571 this.end(head ? null : body);572};573574/**575 * Render `view` with the given `options` and optional callback `fn`.576 * When a callback function is given a response will _not_ be made577 * automatically, otherwise a response of _200_ and _text/html_ is given.578 *579 * Options:580 * 581 * - `status` Response status code (`res.statusCode`)582 * - `charset` Set the charset (`res.charset`)583 *584 * Reserved locals:585 *586 * - `cache` boolean hinting to the engine it should cache587 * - `filename` filename of the view being rendered588 *589 * @param {String} view590 * @param {Object|Function} options or callback function591 * @param {Function} fn592 * @api public593 */594595res.render = function(view, options, fn){596 var self = this597 , options = options || {}598 , req = this.req599 , app = req.app;600601 // support callback function as second arg602 if ('function' == typeof options) {603 fn = options, options = {};604 }605606 function render() {607 // merge res.locals608 options.locals = self.locals;609610 // default callback to respond611 fn = fn || function(err, str){612 if (err) return req.next(err);613 self.send(str);614 };615616 // render617 app.render(view, options, fn);618 }619620 // invoke view callbacks621 var callbacks = app.viewCallbacks622 , pending = callbacks.length623 , len = pending624 , done;625626 if (len) {627 for (var i = 0; i < len; ++i) {628 callbacks[i](req, self, function(err){629 if (done) return;630631 if (err) {632 req.next(err);633 done = true;634 return;635 }636637 --pending || render();638 });639 }640 } else {641 render();642 }643};