Skip to content
Myr

response.js

This file

Path

lib/response.js

461 lines · 11.0 KiB · JavaScript

Last changed by

when cookie path === null dont default itTj Holowaychukbefore adoptionee4471b

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();30 *     res.send(new Buffer('wahoo'));31 *     res.send({ some: 'json' });32 *     res.send('<p>some html</p>');33 *     res.send('Sorry, cant find that', 404);34 *     res.send('text', { 'Content-Type': 'text/plain' }, 201);35 *     res.send(404);36 *37 * @param {String|Object|Number|Buffer} body or status38 * @param {Object|Number} headers or status39 * @param {Number} status40 * @return {ServerResponse}41 * @api public42 */4344res.send = function(body, headers, status){45  // allow status as second arg46  if ('number' == typeof headers) {47    status = headers,48    headers = null;49  }5051  // default status52  status = status || this.statusCode;5354  // allow 0 args as 20455  if (!arguments.length || undefined === body) body = status = 204;5657  // determine content type58  switch (typeof body) {59    case 'number':60      if (!this.header('Content-Type')) {61        this.contentType('.txt');62      }63      body = http.STATUS_CODES[status = body];64      break;65    case 'string':66      if (!this.header('Content-Type')) {67        this.charset = this.charset || 'utf-8';68        this.contentType('.html');69      }70      break;71    case 'boolean':72    case 'object':73      if (Buffer.isBuffer(body)) {74        if (!this.header('Content-Type')) {75          this.contentType('.bin');76        }77      } else {78        if (!this.header('Content-Type')) {79          this.charset = this.charset || 'utf-8';80          this.contentType('.json');81        }82        body = JSON.stringify(body);83        if (this.req.query.callback && this.app.set('jsonp callback')) {84          this.charset = this.charset || 'utf-8';85          this.header('Content-Type', 'text/javascript');86          body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';87        }88      }89      break;90  }9192  // populate Content-Length93  if (!this.header('Content-Length')) {94    this.header('Content-Length', Buffer.isBuffer(body)95      ? body.length96      : Buffer.byteLength(body));97  }9899  // merge headers passed100  if (headers) {101    var fields = Object.keys(headers);102    for (var i = 0, len = fields.length; i < len; ++i) {103      var field = fields[i];104      this.header(field, headers[field]);105    }106  }107108  // strip irrelevant headers109  if (204 == status || 304 == status) {110    this.removeHeader('Content-Type');111    this.removeHeader('Content-Length');112  }113114  // respond115  this.statusCode = status;116  this.end('HEAD' == this.req.method ? undefined : body);117  return this;118};119120/**121 * Send JSON response with `obj`, optional `headers`, and optional `status`.122 *123 * Examples:124 *125 *     res.json(null);126 *     res.json({ user: 'tj' });127 *     res.json('oh noes!', 500);128 *     res.json('I dont have that', 404);129 *130 * @param {Mixed} obj131 * @param {Object|Number} headers or status132 * @param {Number} status133 * @return {ServerResponse}134 * @api public135 */136137res.json = function(obj, headers, status){138  this.charset = this.charset || 'utf-8';139  this.header('Content-Type', 'application/json');140  return this.send(JSON.stringify(obj), headers, status);141};142143/**144 * Set status `code`.145 *146 * @param {Number} code147 * @return {ServerResponse}148 * @api public149 */150151res.status = function(code){152  this.statusCode = code;153  return this;154};155156/**157 * Transfer the file at the given `path`. Automatically sets 158 * the _Content-Type_ response header field. `next()` is called159 * when `path` is a directory, or when an error occurs.160 *161 * Options:162 *163 *   - `maxAge` defaulting to 0164 *   - `root`   root directory for relative filenames165 *166 * @param {String} path167 * @param {Object|Function} options or fn168 * @param {Function} fn169 * @api public170 */171172res.sendfile = function(path, options, fn){173  var next = this.req.next;174  options = options || {};175176  // support function as second arg177  if ('function' == typeof options) {178    fn = options;179    options = {};180  }181182  options.path = encodeURIComponent(path);183  options.callback = fn;184  send(this.req, this, next, options);185};186187/**188 * Set _Content-Type_ response header passed through `mime.lookup()`.189 *190 * Examples:191 *192 *     var filename = 'path/to/image.png';193 *     res.contentType(filename);194 *     // res.headers['Content-Type'] is now "image/png"195 *196 *     res.contentType('.html');197 *     res.contentType('html');198 *     res.contentType('json');199 *     res.contentType('png');200 *201 * @param {String} type202 * @return {String} the resolved mime type203 * @api public204 */205206res.contentType = function(type){207  return this.header('Content-Type', mime.lookup(type));208};209210/**211 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.212 *213 * @param {String} filename214 * @return {ServerResponse}215 * @api public216 */217218res.attachment = function(filename){219  if (filename) this.contentType(filename);220  this.header('Content-Disposition', filename221    ? 'attachment; filename="' + basename(filename) + '"'222    : 'attachment');223  return this;224};225226/**227 * Transfer the file at the given `path`, with optional 228 * `filename` as an attachment and optional callback `fn(err)`,229 * and optional `fn2(err)` which is invoked when an error has230 * occurred after header has been sent.231 *232 * @param {String} path233 * @param {String|Function} filename or fn234 * @param {Function} fn235 * @param {Function} fn2236 * @api public237 */238239res.download = function(path, filename, fn, fn2){240  var self = this;241242  // support callback as second arg243  if ('function' == typeof filename) {244    fn2 = fn;245    fn = filename;246    filename = null;247  }248249  // transfer the file250  this.attachment(filename || path).sendfile(path, function(err){251    var sentHeader = self._header;252    if (err) {253      if (!sentHeader) self.removeHeader('Content-Disposition');254      if (sentHeader) {255        fn2 && fn2(err);256      } else if (fn) {257        fn(err);258      } else {259        self.req.next(err);260      }261    } else if (fn) {262      fn();263    }264  });265};266267/**268 * Set or get response header `name` with optional `val`.269 *270 * @param {String} name271 * @param {String} val272 * @return {String}273 * @api public274 */275276res.header = function(name, val){277  if (val === undefined) {278    return this.getHeader(name);279  } else {280    this.setHeader(name, val);281    return val;282  }283};284285/**286 * Clear cookie `name`.287 *288 * @param {String} name289 * @param {Object} options290 * @api public291 */292293res.clearCookie = function(name, options){294  var opts = { expires: new Date(1) };295  this.cookie(name, '', options296    ? utils.merge(options, opts)297    : opts);298};299300/**301 * Set cookie `name` to `val`, with the given `options`.302 *303 * Options:304 *305 *    - `maxAge`   max-age in milliseconds, converted to `expires`306 *    - `path`     defaults to the "home" setting which is typically "/"307 *308 * Examples:309 *310 *    // "Remember Me" for 15 minutes311 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });312 *313 *    // save as above314 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })315 *316 * @param {String} name317 * @param {String} val318 * @param {Options} options319 * @api public320 */321322res.cookie = function(name, val, options){323  options = options || {};324  if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);325  if (undefined === options.path) options.path = this.app.set('home');326  var cookie = utils.serializeCookie(name, val, options);327  this.header('Set-Cookie', cookie);328};329330/**331 * Redirect to the given `url` with optional response `status`332 * defauling to 302.333 *334 * The given `url` can also be the name of a mapped url, for335 * example by default express supports "back" which redirects336 * to the _Referrer_ or _Referer_ headers or the application's337 * "home" setting. Express also supports "home" out of the box,338 * which can be set via `app.set('home', '/blog');`, and defaults339 * to '/'.340 *341 * Redirect Mapping:342 * 343 *  To extend the redirect mapping capabilities that Express provides,344 *  we may use the `app.redirect()` method:345 * 346 *     app.redirect('google', 'http://google.com');347 * 348 *  Now in a route we may call:349 *350 *     res.redirect('google');351 *352 *  We may also map dynamic redirects:353 *354 *      app.redirect('comments', function(req, res){355 *          return '/post/' + req.params.id + '/comments';356 *      });357 *358 *  So now we may do the following, and the redirect will dynamically adjust to359 *  the context of the request. If we called this route with _GET /post/12_ our360 *  redirect _Location_ would be _/post/12/comments_.361 *362 *      app.get('/post/:id', function(req, res){363 *        res.redirect('comments');364 *      });365 *366 *  Unless an absolute `url` is given, the app's mount-point367 *  will be respected. For example if we redirect to `/posts`,368 *  and our app is mounted at `/blog` we will redirect to `/blog/posts`.369 *370 * @param {String} url371 * @param {Number} code372 * @api public373 */374375res.redirect = function(url, status){376  var app = this.app377    , req = this.req378    , base = app.set('home') || '/'379    , status = status || 302380    , body;381382  // Setup redirect map383  var map = {384      back: req.header('Referrer', base)385    , home: base386  };387388  // Support custom redirect map389  map.__proto__ = app.redirects;390391  // Attempt mapped redirect392  var mapped = 'function' == typeof map[url]393    ? map[url](req, this)394    : map[url];395396  // Perform redirect397  url = mapped || url;398399  // Relative400  if (!~url.indexOf('://')) {401    // Respect mount-point402    if (app.route) url = join(app.route, url);403404    // Absolute405    var host = req.headers.host406      , tls = req.connection.encrypted;407    url = 'http' + (tls ? 's' : '') + '://' + host + url;408  }409  410411  // Support text/{plain,html} by default412  if (req.accepts('html')) {413    body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';414    this.header('Content-Type', 'text/html');415  } else {416    body = http.STATUS_CODES[status] + '. Redirecting to ' + url;417    this.header('Content-Type', 'text/plain');418  }419420  // Respond421  this.statusCode = status;422  this.header('Location', url);423  this.end(body);424};425426/**427 * Assign the view local variable `name` to `val` or return the428 * local previously assigned to `name`.429 *430 * @param {String} name431 * @param {Mixed} val432 * @return {Mixed} val433 * @api public434 */435436res.local = function(name, val){437  this._locals = this._locals || {};438  return undefined === val439    ? this._locals[name]440    : this._locals[name] = val;441};442443/**444 * Assign several locals with the given `obj`,445 * or return the locals.446 *447 * @param {Object} obj448 * @return {Object|Undefined}449 * @api public450 */451452res.locals =453res.helpers = function(obj){454  if (obj) {455    for (var key in obj) {456      this.local(key, obj[key]);457    }458  } else {459    return this._locals;460  }461};