response.js
This file
Path
lib/response.js
561 lines · 12.6 KiB · JavaScript
Last changed by
Removed `res.header(field, value)`TJ Holowaychukbefore adoption76fd462
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 , statusCodes = http.STATUS_CODES18 , send = connect.static.send19 , mime = require('mime')20 , basename = path.basename21 , join = path.join;2223/**24 * Response prototype.25 */2627var res = module.exports = {28 __proto__: http.ServerResponse.prototype29};3031/**32 * Set status `code`.33 *34 * @param {Number} code35 * @return {ServerResponse}36 * @api public37 */3839res.status = function(code){40 this.statusCode = code;41 return this;42};4344/**45 * Set Cache-Control to the given `type` and `options`.46 *47 * Options:48 *49 * - `maxAge` in milliseconds50 *51 * @param {String} type52 * @param {Object} options53 * @return {ServerResponse}54 * @api public55 */5657res.cache = function(type, options){58 var val = type;59 options = options || {};60 if (options.maxAge) val += ', max-age=' + (options.maxAge / 1000); 61 return this.set('Cache-Control', val);62};6364/**65 * Send a response.66 *67 * Examples:68 *69 * res.send(new Buffer('wahoo'));70 * res.send({ some: 'json' });71 * res.send('<p>some html</p>');72 * res.send(404, 'Sorry, cant find that');73 * res.send(404);74 *75 * @param {Mixed} body or status76 * @param {Mixed} body77 * @return {ServerResponse}78 * @api public79 */8081res.send = function(body){82 var req = this.req83 , head = 'HEAD' == req.method;8485 // allow status / body86 if (2 == arguments.length) {87 this.statusCode = body;88 body = arguments[1];89 }9091 switch (typeof body) {92 // response status93 case 'number':94 this.get('Content-Type') || this.contentType('.txt');95 this.statusCode = body;96 body = http.STATUS_CODES[body];97 break;98 // string defaulting to html99 case 'string':100 if (!this.get('Content-Type')) {101 this.charset = this.charset || 'utf-8';102 this.contentType('.html');103 }104 break;105 case 'boolean':106 case 'object':107 if (null == body) {108 body = '';109 } else if (Buffer.isBuffer(body)) {110 this.get('Content-Type') || this.contentType('.bin');111 } else {112 return this.json(body);113 }114 break;115 }116117 // populate Content-Length118 if (undefined !== body && !this.get('Content-Length')) {119 this.set('Content-Length', Buffer.isBuffer(body)120 ? body.length121 : Buffer.byteLength(body));122 }123124 // strip irrelevant headers125 if (204 == this.statusCode || 304 == this.statusCode) {126 this.removeHeader('Content-Type');127 this.removeHeader('Content-Length');128 body = '';129 }130131 // respond132 this.end(head ? null : body);133 return this;134};135136/**137 * Send JSON response.138 *139 * Examples:140 *141 * res.json(null);142 * res.json({ user: 'tj' });143 * res.json(500, 'oh noes!');144 * res.json(404, 'I dont have that');145 *146 * @param {Mixed} obj or status147 * @param {Mixed} obj148 * @return {ServerResponse}149 * @api public150 */151152res.json = function(obj){153 // allow status / body154 if (2 == arguments.length) {155 this.statusCode = obj;156 obj = arguments[1];157 }158159 var settings = this.app.settings160 , jsonp = settings['jsonp callback']161 , replacer = settings['json replacer']162 , spaces = settings['json spaces']163 , body = JSON.stringify(obj, replacer, spaces)164 , callback = this.req.query.callback;165166 this.charset = this.charset || 'utf-8';167 this.set('Content-Type', 'application/json');168169 if (callback && jsonp) {170 this.set('Content-Type', 'text/javascript');171 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';172 }173174 return this.send(body);175};176177/**178 * Transfer the file at the given `path`.179 * 180 * Automatically sets the _Content-Type_ response header field.181 * The callback `fn(err)` is invoked when the transfer is complete182 * or when an error occurs. Be sure to check `res.sentHeader`183 * if you wish to attempt responding, as the header and some data184 * may have already been transferred.185 *186 * Options:187 *188 * - `maxAge` defaulting to 0189 * - `root` root directory for relative filenames190 *191 * @param {String} path192 * @param {Object|Function} options or fn193 * @param {Function} fn194 * @api public195 */196197res.sendfile = function(path, options, fn){198 var self = this199 , req = self.req200 , next = this.req.next201 , options = options || {};202203 // support function as second arg204 if ('function' == typeof options) {205 fn = options;206 options = {};207 }208209 // callback210 options.callback = function(err){211 if (err) {212 // cast ENOENT213 if ('ENOENT' == err.code) err = 404;214215 // coerce numeric error to an Error216 // TODO: remove217 // TODO: remove docs for headerSent?218 if ('number' == typeof err) err = utils.error(err);219220 // ditch content-disposition to prevent funky responses221 if (!self.headerSent) self.removeHeader('Content-Disposition');222223 // woot! callback available224 if (fn) return fn(err);225226 // lost in limbo if there's no callback227 if (self.headerSent) return;228229 return req.next(err);230 }231232 fn && fn();233 };234235 // transfer236 options.path = encodeURIComponent(path);237 send(this.req, this, next, options);238};239240/**241 * Transfer the file at the given `path` as an attachment.242 *243 * Optionally providing an alternate attachment `filename`,244 * and optional callback `fn(err)`. The callback is invoked245 * when the data transfer is complete, or when an error has246 * ocurred. Be sure to check `res.headerSent` if you plan to respond.247 *248 * @param {String} path249 * @param {String|Function} filename or fn250 * @param {Function} fn251 * @api public252 */253254res.download = function(path, filename, fn){255 // support function as second arg256 if ('function' == typeof filename) {257 fn = filename;258 filename = null;259 }260261 return this.attachment(filename || path).sendfile(path, fn);262};263264/**265 * Set _Content-Type_ response header passed through `mime.lookup()`.266 *267 * Examples:268 *269 * var filename = 'path/to/image.png';270 * res.contentType(filename);271 * // res.headers['Content-Type'] is now "image/png"272 *273 * res.contentType('.html');274 * res.contentType('html');275 * res.contentType('json');276 * res.contentType('png');277 * res.type('png');278 *279 * @param {String} type280 * @return {ServerResponse} for chaining281 * @api public282 */283284res.contentType =285res.type = function(type){286 return this.set('Content-Type', mime.lookup(type));287};288289/**290 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.291 *292 * @param {String} filename293 * @return {ServerResponse}294 * @api public295 */296297res.attachment = function(filename){298 if (filename) this.type(filename);299 this.set('Content-Disposition', filename300 ? 'attachment; filename="' + basename(filename) + '"'301 : 'attachment');302 return this;303};304305/**306 * Set header `field` to `val`, or pass307 * an object of of header fields.308 *309 * Examples:310 *311 * res.set('Accept', 'application/json');312 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });313 *314 * @param {String|Object} field315 * @param {String} val316 * @return {ServerResponse} for chaining317 * @api public318 */319320res.set = function(field, val){321 if (2 == arguments.length) {322 this.setHeader(field, val);323 } else {324 for (var key in field) {325 this.setHeader(key, field[key]);326 }327 }328 return this;329};330331/**332 * Get value for header `field`.333 *334 * @param {String} field335 * @return {String}336 * @api public337 */338339res.get = function(field){340 return this.getHeader(field);341};342343/**344 * Clear cookie `name`.345 *346 * @param {String} name347 * @param {Object} options348 * @param {ServerResponse} for chaining349 * @api public350 */351352res.clearCookie = function(name, options){353 var opts = { expires: new Date(1), path: '/' };354 return this.cookie(name, '', options355 ? utils.merge(opts, options)356 : opts);357};358359/**360 * Set a signed cookie with the given `name` and `val`.361 * See `res.cookie()` for details.362 *363 * @param {String} name364 * @param {String|Object} val365 * @param {Object} options366 * @api public367 */368369res.signedCookie = function(name, val, options){370 var secret = this.req.secret;371 if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');372 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);373 val = utils.sign(val, secret);374 return this.cookie(name, val, options);375};376377/**378 * Set cookie `name` to `val`, with the given `options`.379 *380 * Options:381 *382 * - `maxAge` max-age in milliseconds, converted to `expires`383 * - `path` defaults to "/"384 *385 * Examples:386 *387 * // "Remember Me" for 15 minutes388 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });389 *390 * // save as above391 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })392 *393 * @param {String} name394 * @param {String|Object} val395 * @param {Options} options396 * @api public397 */398399res.cookie = function(name, val, options){400 options = options || {};401 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);402 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);403 if (null == options.path) options.path = '/';404 var cookie = utils.serializeCookie(name, val, options);405 this.set('Set-Cookie', cookie);406 return this;407};408409/**410 * Redirect to the given `url` with optional response `status`411 * defaulting to 302.412 *413 * The given `url` can also be the name of a mapped url, for414 * example by default express supports "back" which redirects415 * to the _Referrer_ or _Referer_ headers or "/".416 *417 * Examples:418 *419 * res.redirect('/foo/bar');420 * res.redirect('http://example.com');421 * res.redirect(301, 'http://example.com');422 *423 * Mounting:424 *425 * When an application is mounted, and `res.redirect()`426 * is given a path that does _not_ lead with "/". For 427 * example suppose a "blog" app is mounted at "/blog",428 * the following redirect would result in "/blog/login":429 *430 * res.redirect('login');431 *432 * While the leading slash would result in a redirect to "/login":433 *434 * res.redirect('/login');435 *436 * @param {String} url437 * @param {Number} code438 * @api public439 */440441res.redirect = function(url){442 var app = this.app443 , req = this.req444 , head = 'HEAD' == req.method445 , status = 302446 , body;447448 // allow status / url449 if (2 == arguments.length) {450 status = url;451 url = arguments[1];452 }453454 // setup redirect map455 var map = { back: req.get('Referrer') || '/' };456457 // perform redirect458 url = map[url] || url;459460 // relative461 if (!~url.indexOf('://')) {462 var path = app.path();463464 // relative to path465 if (0 == url.indexOf('./') || 0 == url.indexOf('..')) {466 url = req.path + '/' + url;467 // relative to mount-point468 } else if ('/' != url[0]) {469 url = path + '/' + url;470 }471472 // Absolute473 var host = req.get('Host');474 url = req.protocol + '://' + host + url;475 }476477 // Support text/{plain,html} by default478 if (req.accepts('html')) {479 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';480 this.set('Content-Type', 'text/html');481 } else {482 body = statusCodes[status] + '. Redirecting to ' + url;483 this.set('Content-Type', 'text/plain');484 }485486 // Respond487 this.statusCode = status;488 this.set('Location', url);489 this.end(head ? null : body);490};491492/**493 * Render `view` with the given `options` and optional callback `fn`.494 * When a callback function is given a response will _not_ be made495 * automatically, otherwise a response of _200_ and _text/html_ is given.496 *497 * Options:498 * 499 * - `status` Response status code (`res.statusCode`)500 * - `charset` Set the charset (`res.charset`)501 *502 * Reserved locals:503 *504 * - `cache` boolean hinting to the engine it should cache505 * - `filename` filename of the view being rendered506 *507 * @param {String} view508 * @param {Object|Function} options or callback function509 * @param {Function} fn510 * @api public511 */512513res.render = function(view, options, fn){514 var self = this515 , options = options || {}516 , req = this.req517 , app = req.app;518519 // support callback function as second arg520 if ('function' == typeof options) {521 fn = options, options = {};522 }523524 function render() {525 // merge res.locals526 options.locals = self.locals;527528 // default callback to respond529 fn = fn || function(err, str){530 if (err) return req.next(err);531 self.send(str);532 };533534 // render535 app.render(view, options, fn);536 }537538 // invoke view callbacks539 var callbacks = app.viewCallbacks540 , pending = callbacks.length541 , len = pending542 , done;543544 if (len) {545 for (var i = 0; i < len; ++i) {546 callbacks[i](req, self, function(err){547 if (done) return;548549 if (err) {550 req.next(err);551 done = true;552 return;553 }554555 --pending || render();556 });557 }558 } else {559 render();560 }561};