Skip to content
Myr

response.js

This file

Path

lib/response.js

550 lines · 12.7 KiB · JavaScript

Last changed by

Added replacement for dynamic locals. Closes #788Tj Holowaychukbefore adoption73f1da2

History of this file

Take 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  , res = http.ServerResponse.prototype19  , send = connect.static.send20  , mime = require('mime')21  , basename = path.basename22  , join = path.join;2324/**25 * Send a response.26 *27 * Examples:28 *29 *     res.send(new Buffer('wahoo'));30 *     res.send({ some: 'json' });31 *     res.send('<p>some html</p>');32 *     res.send(404, 'Sorry, cant find that');33 *     res.send(404);34 *35 * @param {Mixed} body or status36 * @param {Mixed} body37 * @return {ServerResponse}38 * @api public39 */4041res.send = function(body){42  var req = this.req43    , head = 'HEAD' == req.method;4445  // allow status / body46  if (2 == arguments.length) {47    this.statusCode = body;48    body = arguments[1];49  }5051  switch (typeof body) {52    // response status53    case 'number':54      this.header('Content-Type') || this.contentType('.txt');55      this.statusCode = body;56      body = http.STATUS_CODES[body];57      break;58    // string defaulting to html59    case 'string':60      if (!this.header('Content-Type')) {61        this.charset = this.charset || 'utf-8';62        this.contentType('.html');63      }64      break;65    case 'boolean':66    case 'object':67      if (null == body) {68        body = '';69      } else if (Buffer.isBuffer(body)) {70        this.header('Content-Type') || this.contentType('.bin');71      } else {72        return this.json(body);73      }74      break;75  }7677  // populate Content-Length78  if (undefined !== body && !this.header('Content-Length')) {79    this.header('Content-Length', Buffer.isBuffer(body)80      ? body.length81      : Buffer.byteLength(body));82  }8384  // strip irrelevant headers85  if (204 == this.statusCode || 304 == this.statusCode) {86    this.removeHeader('Content-Type');87    this.removeHeader('Content-Length');88    body = '';89  }9091  // respond92  this.end(head ? null : body);93  return this;94};9596/**97 * Send JSON response.98 *99 * Examples:100 *101 *     res.json(null);102 *     res.json({ user: 'tj' });103 *     res.json(500, 'oh noes!');104 *     res.json(404, 'I dont have that');105 *106 * @param {Mixed} obj or status107 * @param {Mixed} obj108 * @return {ServerResponse}109 * @api public110 */111112res.json = function(obj){113  // allow status / body114  if (2 == arguments.length) {115    this.statusCode = obj;116    obj = arguments[1];117  }118119  var body = JSON.stringify(obj)120    , callback = this.req.query.callback121    , jsonp = this.app.enabled('jsonp callback');122123  this.charset = this.charset || 'utf-8';124  this.header('Content-Type', 'application/json');125126  if (callback && jsonp) {127    this.header('Content-Type', 'text/javascript');128    body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';129  }130131  return this.send(body);132};133134/**135 * Set status `code`.136 *137 * @param {Number} code138 * @return {ServerResponse}139 * @api public140 */141142res.status = function(code){143  this.statusCode = code;144  return this;145};146147/**148 * Transfer the file at the given `path`.149 * 150 * Automatically sets the _Content-Type_ response header field.151 * The callback `fn(err)` is invoked when the transfer is complete152 * or when an error occurs. Be sure to check `res.sentHeader`153 * if you wish to attempt responding, as the header and some data154 * may have already been transferred.155 *156 * Options:157 *158 *   - `maxAge` defaulting to 0159 *   - `root`   root directory for relative filenames160 *161 * @param {String} path162 * @param {Object|Function} options or fn163 * @param {Function} fn164 * @api public165 */166167res.sendfile = function(path, options, fn){168  var self = this169    , req = self.req170    , next = this.req.next171    , options = options || {};172173  // support function as second arg174  if ('function' == typeof options) {175    fn = options;176    options = {};177  }178179  // callback180  options.callback = function(err){181    // TODO: remove when node adds this182    self.sentHeader = !! self._header;183184    // error185    if (err) {186      // ditch content-disposition to prevent funky responses187      if (!self.sentHeader) self.removeHeader('Content-Disposition');188189      // not found190      if ('ENOENT' == err.code) return req.next();191192      // lost in limbo if there's no callback193      if (self.sentHeader) return fn && fn(err);194195      // callback available196      if (fn) return fn(err);197198      return req.next(err);199    }200201    fn && fn();202  };203204  // transfer205  options.path = encodeURIComponent(path);206  send(this.req, this, next, options);207};208209/**210 * Transfer the file at the given `path` as an attachment.211 *212 * Optionally providing an alternate attachment `filename`,213 * and optional callback `fn(err)`. The callback is invoked214 * when the data transfer is complete, or when an error has215 * ocurred. Be sure to check `res.sendHeader` if you plan to respond.216 *217 * @param {String} path218 * @param {String|Function} filename or fn219 * @param {Function} fn220 * @api public221 */222223res.download = function(path, filename, fn){224  // support function as second arg225  if ('function' == typeof filename) {226    fn = filename;227    filename = null;228  }229230  return this.attachment(filename || path).sendfile(path, fn);231};232233/**234 * Set _Content-Type_ response header passed through `mime.lookup()`.235 *236 * Examples:237 *238 *     var filename = 'path/to/image.png';239 *     res.contentType(filename);240 *     // res.headers['Content-Type'] is now "image/png"241 *242 *     res.contentType('.html');243 *     res.contentType('html');244 *     res.contentType('json');245 *     res.contentType('png');246 *     res.type('png');247 *248 * @param {String} type249 * @return {ServerResponse} for chaining250 * @api public251 */252253res.contentType =254res.type = function(type){255  return this.header('Content-Type', mime.lookup(type));256};257258/**259 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.260 *261 * @param {String} filename262 * @return {ServerResponse}263 * @api public264 */265266res.attachment = function(filename){267  if (filename) this.contentType(filename);268  this.header('Content-Disposition', filename269    ? 'attachment; filename="' + basename(filename) + '"'270    : 'attachment');271  return this;272};273274/**275 * Set header `field` to `val`, or pass276 * an object of of header fields.277 *278 * Examples:279 *280 *    res.set('Accept', 'application/json');281 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });282 *283 * @param {String|Object} field284 * @param {String} val285 * @return {ServerResponse} for chaining286 * @api public287 */288289res.set = function(field, val){290  if (2 == arguments.length) {291    this.setHeader(field, val);292  } else {293    for (var key in field) {294      this.setHeader(key, field[key]);295    }296  }297  return this;298};299300/**301 * Get value for header `field`.302 *303 * @param {String} field304 * @return {String}305 * @api public306 */307308res.get = function(field){309  return this.getHeader(field);310};311312/**313 * Set or get response header `field` with optional `val`.314 *315 * @param {String} name316 * @param {String} val317 * @return {ServerResponse} for chaining318 * @api public319 */320321res.header = function(field, val){322  if (1 == arguments.length) return this.getHeader(field);323  this.setHeader(field, val);324  return this;325};326327/**328 * Clear cookie `name`.329 *330 * @param {String} name331 * @param {Object} options332 * @param {ServerResponse} for chaining333 * @api public334 */335336res.clearCookie = function(name, options){337  var opts = { expires: new Date(1) };338  return this.cookie(name, '', options339    ? utils.merge(options, opts)340    : opts);341};342343/**344 * Set cookie `name` to `val`, with the given `options`.345 *346 * Options:347 *348 *    - `maxAge`   max-age in milliseconds, converted to `expires`349 *    - `path`     defaults to the "basepath" setting which is typically "/"350 *351 * Examples:352 *353 *    // "Remember Me" for 15 minutes354 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });355 *356 *    // save as above357 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })358 *359 * @param {String} name360 * @param {String} val361 * @param {Options} options362 * @api public363 */364365res.cookie = function(name, val, options){366  options = options || {};367  if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);368  if (undefined === options.path) options.path = this.app.set('basepath');369  var cookie = utils.serializeCookie(name, val, options);370  this.header('Set-Cookie', cookie);371  return this;372};373374/**375 * Redirect to the given `url` with optional response `status`376 * defaulting to 302.377 *378 * The given `url` can also be the name of a mapped url, for379 * example by default express supports "back" which redirects380 * to the _Referrer_ or _Referer_ headers or the application's381 * "basepath" setting. Express also supports "basepath" out of the box,382 * which can be set via `app.set('basepath', '/blog');`.383 *384 * Examples:385 *386 *    res.redirect('/foo/bar');387 *    res.redirect('http://example.com');388 *    res.redirect(301, 'http://example.com');389 *390 * Redirect Mapping:391 * 392 *  To extend the redirect mapping capabilities that Express provides,393 *  we may use the `app.redirect()` method:394 * 395 *     app.redirect('google', 'http://google.com');396 * 397 *  Now in a route we may call:398 *399 *     res.redirect('google');400 *401 *  We may also map dynamic redirects:402 *403 *      app.redirect('comments', function(req, res){404 *          return '/post/' + req.params.id + '/comments';405 *      });406 *407 *  So now we may do the following, and the redirect will dynamically adjust to408 *  the context of the request. If we called this route with _GET /post/12_ our409 *  redirect _Location_ would be _/post/12/comments_.410 *411 *      app.get('/post/:id', function(req, res){412 *        res.redirect('comments');413 *      });414 *415 *  Unless an absolute `url` is given, the app's mount-point416 *  will be respected. For example if we redirect to `/posts`,417 *  and our app is mounted at `/blog` we will redirect to `/blog/posts`.418 *419 * @param {String} url420 * @param {Number} code421 * @api public422 */423424res.redirect = function(url){425  var app = this.app426    , req = this.req427    , base = app.set('basepath') || app.route428    , head = 'HEAD' == req.method429    , status = 302430    , body;431432  // allow status / url433  if (2 == arguments.length) {434    status = url;435    url = arguments[1];436  }437438  // Setup redirect map439  var map = {440      back: req.header('Referrer', base)441    , home: base442  };443444  // Support custom redirect map445  map.__proto__ = app.redirects;446447  // Attempt mapped redirect448  var mapped = 'function' == typeof map[url]449    ? map[url](req, this)450    : map[url];451452  // Perform redirect453  url = mapped || url;454455  // Relative456  if (!~url.indexOf('://')) {457    // Respect mount-point458    if ('/' != base && 0 != url.indexOf(base)) url = base + url;459460    // Absolute461    var host = req.headers.host462      , tls = req.connection.encrypted;463    url = 'http' + (tls ? 's' : '') + '://' + host + url;464  }465466  // Support text/{plain,html} by default467  if (req.accepts('html')) {468    body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';469    this.header('Content-Type', 'text/html');470  } else {471    body = statusCodes[status] + '. Redirecting to ' + url;472    this.header('Content-Type', 'text/plain');473  }474475  // Respond476  this.statusCode = status;477  this.header('Location', url);478  this.end(head ? null : body);479};480481/**482 * Render `view` with the given `options` and optional callback `fn`.483 * When a callback function is given a response will _not_ be made484 * automatically, otherwise a response of _200_ and _text/html_ is given.485 *486 * Options:487 *  488 *  - `status`    Response status code (`res.statusCode`)489 *  - `charset`   Set the charset (`res.charset`)490 *491 * Reserved locals:492 *493 *  - `cache`     boolean hinting to the engine it should cache494 *  - `filename`  filename of the view being rendered495 *496 * @param  {String} view497 * @param  {Object|Function} options or callback function498 * @param  {Function} fn499 * @api public500 */501502res.render = function(view, options, fn){503  var self = this504    , options = options || {}505    , req = this.req506    , app = req.app;507508  // support callback function as second arg509  if ('function' == typeof options) {510    fn = options, options = {};511  }512513  function render() {514    // merge res.locals515    options.locals = self.locals;516517    // status option518    if (options.status) self.statusCode = options.status;519520    // charset option521    if (options.charset) self.charset = options.charset;522523    // default callback to respond524    fn = fn || function(err, str){525      if (err) return req.next(err);526      self.send(str);527    };528529    // render530    app.render(view, options, fn);531  }532533  // invoke view callbacks534  var callbacks = app.viewCallbacks535    , pending = callbacks.length536    , len = pending537    , done;538539  for (var i = 0; i < len; ++i) {540    callbacks[i](req, self, function(err){541      if (err) {542        req.next(err);543        done = true;544        return;545      }546547      --pending || render();548    });549  }550};