Skip to content
Myr

response.js

This file

Path

lib/response.js

404 lines · 9.5 KiB · JavaScript

Last changed by

chainable `res.header()`Tj Holowaychukbefore adoption41568b7

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 `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(404);34 *35 * @param {String|Object|Number|Buffer} body or status36 * @param {Number} status37 * @return {ServerResponse}38 * @api public39 */4041res.send = function(body, status){42  // default status43  status = status || this.statusCode;4445  // determine content type46  switch (typeof body) {47    case 'number':48      if (!this.header('Content-Type')) {49        this.contentType('.txt');50      }51      body = http.STATUS_CODES[status = body];52      break;53    case 'string':54      if (!this.header('Content-Type')) {55        this.charset = this.charset || 'utf-8';56        this.contentType('.html');57      }58      break;59    case 'boolean':60    case 'object':61      if (Buffer.isBuffer(body)) {62        if (!this.header('Content-Type')) {63          this.contentType('.bin');64        }65      } else {66        return this.json(body, status);67      }68      break;69  }7071  // populate Content-Length72  if (!this.header('Content-Length')) {73    this.header('Content-Length', Buffer.isBuffer(body)74      ? body.length75      : Buffer.byteLength(body));76  }7778  // strip irrelevant headers79  if (204 == status || 304 == status) {80    this.removeHeader('Content-Type');81    this.removeHeader('Content-Length');82  }8384  // respond85  this.statusCode = status;86  this.end('HEAD' == this.req.method ? undefined : body);87  return this;88};8990/**91 * Send JSON response with `obj` and optional `status`.92 *93 * Examples:94 *95 *     res.json(null);96 *     res.json({ user: 'tj' });97 *     res.json('oh noes!', 500);98 *     res.json('I dont have that', 404);99 *100 * @param {Mixed} obj101 * @param {Number} status102 * @param {Number} status103 * @return {ServerResponse}104 * @api public105 */106107res.json = function(obj, status){108  var body = JSON.stringify(obj)109    , callback = this.req.query.callback110    , jsonp = this.app.enabled('jsonp callback');111112  this.charset = this.charset || 'utf-8';113  this.header('Content-Type', 'application/json');114115  if (callback && jsonp) {116    this.header('Content-Type', 'text/javascript');117    body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';118  }119120  return this.send(body, status);121};122123/**124 * Set status `code`.125 *126 * @param {Number} code127 * @return {ServerResponse}128 * @api public129 */130131res.status = function(code){132  this.statusCode = code;133  return this;134};135136/**137 * Transfer the file at the given `path`. Automatically sets 138 * the _Content-Type_ response header field. `next()` is called139 * when `path` is a directory, or when an error occurs.140 *141 * Options:142 *143 *   - `maxAge` defaulting to 0144 *   - `root`   root directory for relative filenames145 *146 * @param {String} path147 * @param {Object|Function} options or fn148 * @param {Function} fn149 * @api public150 */151152res.sendfile = function(path, options, fn){153  var next = this.req.next;154  options = options || {};155156  // support function as second arg157  if ('function' == typeof options) {158    fn = options;159    options = {};160  }161162  options.path = encodeURIComponent(path);163  options.callback = fn;164  send(this.req, this, next, options);165};166167/**168 * Set _Content-Type_ response header passed through `mime.lookup()`.169 *170 * Examples:171 *172 *     var filename = 'path/to/image.png';173 *     res.contentType(filename);174 *     // res.headers['Content-Type'] is now "image/png"175 *176 *     res.contentType('.html');177 *     res.contentType('html');178 *     res.contentType('json');179 *     res.contentType('png');180 *181 * @param {String} type182 * @return {String} the resolved mime type183 * @api public184 */185186res.contentType = function(type){187  return this.header('Content-Type', mime.lookup(type));188};189190/**191 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.192 *193 * @param {String} filename194 * @return {ServerResponse}195 * @api public196 */197198res.attachment = function(filename){199  if (filename) this.contentType(filename);200  this.header('Content-Disposition', filename201    ? 'attachment; filename="' + basename(filename) + '"'202    : 'attachment');203  return this;204};205206/**207 * Transfer the file at the given `path`, with optional 208 * `filename` as an attachment and optional callback `fn(err)`,209 * and optional `fn2(err)` which is invoked when an error has210 * occurred after header has been sent.211 *212 * @param {String} path213 * @param {String|Function} filename or fn214 * @param {Function} fn215 * @param {Function} fn2216 * @api public217 */218219res.download = function(path, filename, fn, fn2){220  var self = this;221222  // support callback as second arg223  if ('function' == typeof filename) {224    fn2 = fn;225    fn = filename;226    filename = null;227  }228229  // transfer the file230  this.attachment(filename || path).sendfile(path, function(err){231    var sentHeader = self._header;232    if (err) {233      if (!sentHeader) self.removeHeader('Content-Disposition');234      if (sentHeader) {235        fn2 && fn2(err);236      } else if (fn) {237        fn(err);238      } else {239        self.req.next(err);240      }241    } else if (fn) {242      fn();243    }244  });245};246247/**248 * Set or get response header `name` with optional `val`.249 *250 * @param {String} name251 * @param {String} val252 * @return {ServerResponse} for chaining253 * @api public254 */255256res.header = function(name, val){257  if (1 == arguments.length) {258    return this.getHeader(name);259  } else {260    this.setHeader(name, val);261    return this;262  }263};264265/**266 * Clear cookie `name`.267 *268 * @param {String} name269 * @param {Object} options270 * @api public271 */272273res.clearCookie = function(name, options){274  var opts = { expires: new Date(1) };275  this.cookie(name, '', options276    ? utils.merge(options, opts)277    : opts);278};279280/**281 * Set cookie `name` to `val`, with the given `options`.282 *283 * Options:284 *285 *    - `maxAge`   max-age in milliseconds, converted to `expires`286 *    - `path`     defaults to the "home" setting which is typically "/"287 *288 * Examples:289 *290 *    // "Remember Me" for 15 minutes291 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });292 *293 *    // save as above294 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })295 *296 * @param {String} name297 * @param {String} val298 * @param {Options} options299 * @api public300 */301302res.cookie = function(name, val, options){303  options = options || {};304  if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);305  if (undefined === options.path) options.path = this.app.set('home');306  var cookie = utils.serializeCookie(name, val, options);307  this.header('Set-Cookie', cookie);308};309310/**311 * Redirect to the given `url` with optional response `status`312 * defauling to 302.313 *314 * The given `url` can also be the name of a mapped url, for315 * example by default express supports "back" which redirects316 * to the _Referrer_ or _Referer_ headers or the application's317 * "home" setting. Express also supports "home" out of the box,318 * which can be set via `app.set('home', '/blog');`, and defaults319 * to '/'.320 *321 * Redirect Mapping:322 * 323 *  To extend the redirect mapping capabilities that Express provides,324 *  we may use the `app.redirect()` method:325 * 326 *     app.redirect('google', 'http://google.com');327 * 328 *  Now in a route we may call:329 *330 *     res.redirect('google');331 *332 *  We may also map dynamic redirects:333 *334 *      app.redirect('comments', function(req, res){335 *          return '/post/' + req.params.id + '/comments';336 *      });337 *338 *  So now we may do the following, and the redirect will dynamically adjust to339 *  the context of the request. If we called this route with _GET /post/12_ our340 *  redirect _Location_ would be _/post/12/comments_.341 *342 *      app.get('/post/:id', function(req, res){343 *        res.redirect('comments');344 *      });345 *346 *  Unless an absolute `url` is given, the app's mount-point347 *  will be respected. For example if we redirect to `/posts`,348 *  and our app is mounted at `/blog` we will redirect to `/blog/posts`.349 *350 * @param {String} url351 * @param {Number} code352 * @api public353 */354355res.redirect = function(url, status){356  var app = this.app357    , req = this.req358    , base = app.set('home') || '/'359    , status = status || 302360    , body;361362  // Setup redirect map363  var map = {364      back: req.header('Referrer', base)365    , home: base366  };367368  // Support custom redirect map369  map.__proto__ = app.redirects;370371  // Attempt mapped redirect372  var mapped = 'function' == typeof map[url]373    ? map[url](req, this)374    : map[url];375376  // Perform redirect377  url = mapped || url;378379  // Relative380  if (!~url.indexOf('://')) {381    // Respect mount-point382    if (app.route) url = join(app.route, url);383384    // Absolute385    var host = req.headers.host386      , tls = req.connection.encrypted;387    url = 'http' + (tls ? 's' : '') + '://' + host + url;388  }389  390391  // Support text/{plain,html} by default392  if (req.accepts('html')) {393    body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';394    this.header('Content-Type', 'text/html');395  } else {396    body = http.STATUS_CODES[status] + '. Redirecting to ' + url;397    this.header('Content-Type', 'text/plain');398  }399400  // Respond401  this.statusCode = status;402  this.header('Location', url);403  this.end(body);404};