Skip to content
Myr

response.js

This file

Path

lib/response.js

455 lines · 10.7 KiB · JavaScript

Last changed by

Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994

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  , parseRange = require('./utils').parseRange18  , res = http.ServerResponse.prototype19  , send = connect.static.send20  , mime = require('mime')21  , basename = path.basename22  , join = path.join;2324/**25 * Send a response with the given `body` and optional `headers` and `status` code.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('Sorry, cant find that', 404);33 *     res.send('text', { 'Content-Type': 'text/plain' }, 201);34 *     res.send(404);35 *36 * @param {String|Object|Number|Buffer} body or status37 * @param {Object|Number} headers or status38 * @param {Number} status39 * @return {ServerResponse}40 * @api public41 */4243res.send = function(body, headers, status){44  // allow status as second arg45  if ('number' == typeof headers) {46    status = headers,47    headers = null;48  }4950  // default status51  status = status || this.statusCode;5253  // determine content type54  switch (typeof body) {55    case 'number':56      if (!this.header('Content-Type')) {57        this.contentType('.txt');58      }59      body = http.STATUS_CODES[status = body];60      break;61    case 'string':62      if (!this.header('Content-Type')) {63        this.charset = this.charset || 'utf-8';64        this.contentType('.html');65      }66      break;67    case 'boolean':68    case 'object':69      if (Buffer.isBuffer(body)) {70        if (!this.header('Content-Type')) {71          this.contentType('.bin');72        }73      } else {74        return this.json(body, headers, status);75      }76      break;77  }7879  // populate Content-Length80  if (!this.header('Content-Length')) {81    this.header('Content-Length', Buffer.isBuffer(body)82      ? body.length83      : Buffer.byteLength(body));84  }8586  // merge headers passed87  if (headers) {88    var fields = Object.keys(headers);89    for (var i = 0, len = fields.length; i < len; ++i) {90      var field = fields[i];91      this.header(field, headers[field]);92    }93  }9495  // strip irrelevant headers96  if (204 == status || 304 == status) {97    this.removeHeader('Content-Type');98    this.removeHeader('Content-Length');99  }100101  // respond102  this.statusCode = status;103  this.end('HEAD' == this.req.method ? undefined : body);104  return this;105};106107/**108 * Send JSON response with `obj`, optional `headers`, and optional `status`.109 *110 * Examples:111 *112 *     res.json(null);113 *     res.json({ user: 'tj' });114 *     res.json('oh noes!', 500);115 *     res.json('I dont have that', 404);116 *117 * @param {Mixed} obj118 * @param {Object|Number} headers or status119 * @param {Number} status120 * @return {ServerResponse}121 * @api public122 */123124res.json = function(obj, headers, status){125  var body = JSON.stringify(obj)126    , callback = this.req.query.callback127    , jsonp = this.app.enabled('jsonp callback');128129  this.charset = this.charset || 'utf-8';130  this.header('Content-Type', 'application/json');131132  if (callback && jsonp) {133    this.header('Content-Type', 'text/javascript');134    body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';135  }136137  return this.send(body, headers, status);138};139140/**141 * Set status `code`.142 *143 * @param {Number} code144 * @return {ServerResponse}145 * @api public146 */147148res.status = function(code){149  this.statusCode = code;150  return this;151};152153/**154 * Transfer the file at the given `path`. Automatically sets 155 * the _Content-Type_ response header field. `next()` is called156 * when `path` is a directory, or when an error occurs.157 *158 * Options:159 *160 *   - `maxAge` defaulting to 0161 *   - `root`   root directory for relative filenames162 *163 * @param {String} path164 * @param {Object|Function} options or fn165 * @param {Function} fn166 * @api public167 */168169res.sendfile = function(path, options, fn){170  var next = this.req.next;171  options = options || {};172173  // support function as second arg174  if ('function' == typeof options) {175    fn = options;176    options = {};177  }178179  options.path = encodeURIComponent(path);180  options.callback = fn;181  send(this.req, this, next, options);182};183184/**185 * Set _Content-Type_ response header passed through `mime.lookup()`.186 *187 * Examples:188 *189 *     var filename = 'path/to/image.png';190 *     res.contentType(filename);191 *     // res.headers['Content-Type'] is now "image/png"192 *193 *     res.contentType('.html');194 *     res.contentType('html');195 *     res.contentType('json');196 *     res.contentType('png');197 *198 * @param {String} type199 * @return {String} the resolved mime type200 * @api public201 */202203res.contentType = function(type){204  return this.header('Content-Type', mime.lookup(type));205};206207/**208 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.209 *210 * @param {String} filename211 * @return {ServerResponse}212 * @api public213 */214215res.attachment = function(filename){216  if (filename) this.contentType(filename);217  this.header('Content-Disposition', filename218    ? 'attachment; filename="' + basename(filename) + '"'219    : 'attachment');220  return this;221};222223/**224 * Transfer the file at the given `path`, with optional 225 * `filename` as an attachment and optional callback `fn(err)`,226 * and optional `fn2(err)` which is invoked when an error has227 * occurred after header has been sent.228 *229 * @param {String} path230 * @param {String|Function} filename or fn231 * @param {Function} fn232 * @param {Function} fn2233 * @api public234 */235236res.download = function(path, filename, fn, fn2){237  var self = this;238239  // support callback as second arg240  if ('function' == typeof filename) {241    fn2 = fn;242    fn = filename;243    filename = null;244  }245246  // transfer the file247  this.attachment(filename || path).sendfile(path, function(err){248    var sentHeader = self._header;249    if (err) {250      if (!sentHeader) self.removeHeader('Content-Disposition');251      if (sentHeader) {252        fn2 && fn2(err);253      } else if (fn) {254        fn(err);255      } else {256        self.req.next(err);257      }258    } else if (fn) {259      fn();260    }261  });262};263264/**265 * Set or get response header `name` with optional `val`.266 *267 * @param {String} name268 * @param {String} val269 * @return {String}270 * @api public271 */272273res.header = function(name, val){274  if (val === undefined) {275    return this.getHeader(name);276  } else {277    this.setHeader(name, val);278    return val;279  }280};281282/**283 * Clear cookie `name`.284 *285 * @param {String} name286 * @param {Object} options287 * @api public288 */289290res.clearCookie = function(name, options){291  var opts = { expires: new Date(1) };292  this.cookie(name, '', options293    ? utils.merge(options, opts)294    : opts);295};296297/**298 * Set cookie `name` to `val`, with the given `options`.299 *300 * Options:301 *302 *    - `maxAge`   max-age in milliseconds, converted to `expires`303 *    - `path`     defaults to the "home" setting which is typically "/"304 *305 * Examples:306 *307 *    // "Remember Me" for 15 minutes308 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });309 *310 *    // save as above311 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })312 *313 * @param {String} name314 * @param {String} val315 * @param {Options} options316 * @api public317 */318319res.cookie = function(name, val, options){320  options = options || {};321  if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);322  if (undefined === options.path) options.path = this.app.set('home');323  var cookie = utils.serializeCookie(name, val, options);324  this.header('Set-Cookie', cookie);325};326327/**328 * Redirect to the given `url` with optional response `status`329 * defauling to 302.330 *331 * The given `url` can also be the name of a mapped url, for332 * example by default express supports "back" which redirects333 * to the _Referrer_ or _Referer_ headers or the application's334 * "home" setting. Express also supports "home" out of the box,335 * which can be set via `app.set('home', '/blog');`, and defaults336 * to '/'.337 *338 * Redirect Mapping:339 * 340 *  To extend the redirect mapping capabilities that Express provides,341 *  we may use the `app.redirect()` method:342 * 343 *     app.redirect('google', 'http://google.com');344 * 345 *  Now in a route we may call:346 *347 *     res.redirect('google');348 *349 *  We may also map dynamic redirects:350 *351 *      app.redirect('comments', function(req, res){352 *          return '/post/' + req.params.id + '/comments';353 *      });354 *355 *  So now we may do the following, and the redirect will dynamically adjust to356 *  the context of the request. If we called this route with _GET /post/12_ our357 *  redirect _Location_ would be _/post/12/comments_.358 *359 *      app.get('/post/:id', function(req, res){360 *        res.redirect('comments');361 *      });362 *363 *  Unless an absolute `url` is given, the app's mount-point364 *  will be respected. For example if we redirect to `/posts`,365 *  and our app is mounted at `/blog` we will redirect to `/blog/posts`.366 *367 * @param {String} url368 * @param {Number} code369 * @api public370 */371372res.redirect = function(url, status){373  var app = this.app374    , req = this.req375    , base = app.set('home') || '/'376    , status = status || 302377    , body;378379  // Setup redirect map380  var map = {381      back: req.header('Referrer', base)382    , home: base383  };384385  // Support custom redirect map386  map.__proto__ = app.redirects;387388  // Attempt mapped redirect389  var mapped = 'function' == typeof map[url]390    ? map[url](req, this)391    : map[url];392393  // Perform redirect394  url = mapped || url;395396  // Relative397  if (!~url.indexOf('://')) {398    // Respect mount-point399    if (app.route) url = join(app.route, url);400401    // Absolute402    var host = req.headers.host403      , tls = req.connection.encrypted;404    url = 'http' + (tls ? 's' : '') + '://' + host + url;405  }406  407408  // Support text/{plain,html} by default409  if (req.accepts('html')) {410    body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';411    this.header('Content-Type', 'text/html');412  } else {413    body = http.STATUS_CODES[status] + '. Redirecting to ' + url;414    this.header('Content-Type', 'text/plain');415  }416417  // Respond418  this.statusCode = status;419  this.header('Location', url);420  this.end(body);421};422423/**424 * Assign the view local variable `name` to `val` or return the425 * local previously assigned to `name`.426 *427 * @param {String} name428 * @param {Mixed} val429 * @return {Mixed} val430 * @api public431 */432433res.local = function(name, val){434  this._locals = this._locals || {};435  return undefined === val436    ? this._locals[name]437    : this._locals[name] = val;438};439440/**441 * Assign several locals with the given `obj`,442 * or return the locals.443 *444 * @param {Object} obj445 * @return {Object|ServerResponse}446 * @api public447 */448449res.locals = function(obj){450  if (0 == arguments.length) return this._locals;451  for (var key in obj) {452    this.local(key, obj[key]);453  }454  return this;455};