Skip to content
Myr

response.js

This file

Path

lib/response.js

480 lines · 11.2 KiB · JavaScript

Last changed by

Added support for `res.set(obj)`. Closes #834Tj Holowaychukbefore adoption021655a

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  , parseRange = require('./utils').parseRange19  , res = http.ServerResponse.prototype20  , send = connect.static.send21  , mime = require('mime')22  , basename = path.basename23  , join = path.join;2425/**26 * Send a response.27 *28 * Examples:29 *30 *     res.send(new Buffer('wahoo'));31 *     res.send({ some: 'json' });32 *     res.send('<p>some html</p>');33 *     res.send(404, 'Sorry, cant find that');34 *     res.send(404);35 *36 * @param {Mixed} body or status37 * @param {Mixed} body38 * @return {ServerResponse}39 * @api public40 */4142res.send = function(body){43  var req = this.req44    , head = 'HEAD' == req.method;4546  // allow status / body47  if (2 == arguments.length) {48    this.statusCode = body;49    body = arguments[1];50  }5152  switch (typeof body) {53    // response status54    case 'number':55      this.header('Content-Type') || this.contentType('.txt');56      this.statusCode = body;57      body = http.STATUS_CODES[body];58      break;59    // string defaulting to html60    case 'string':61      if (!this.header('Content-Type')) {62        this.charset = this.charset || 'utf-8';63        this.contentType('.html');64      }65      break;66    case 'boolean':67    case 'object':68      if (null == body) {69        body = '';70      } else if (Buffer.isBuffer(body)) {71        this.header('Content-Type') || this.contentType('.bin');72      } else {73        return this.json(body);74      }75      break;76  }7778  // populate Content-Length79  if (undefined !== body && !this.header('Content-Length')) {80    this.header('Content-Length', Buffer.isBuffer(body)81      ? body.length82      : Buffer.byteLength(body));83  }8485  // strip irrelevant headers86  if (204 == this.statusCode || 304 == this.statusCode) {87    this.removeHeader('Content-Type');88    this.removeHeader('Content-Length');89    body = '';90  }9192  // respond93  this.end(head ? null : body);94  return this;95};9697/**98 * Send JSON response.99 *100 * Examples:101 *102 *     res.json(null);103 *     res.json({ user: 'tj' });104 *     res.json(500, 'oh noes!');105 *     res.json(404, 'I dont have that');106 *107 * @param {Mixed} obj or status108 * @param {Mixed} obj109 * @return {ServerResponse}110 * @api public111 */112113res.json = function(obj){114  // allow status / body115  if (2 == arguments.length) {116    this.statusCode = obj;117    obj = arguments[1];118  }119120  var body = JSON.stringify(obj)121    , callback = this.req.query.callback122    , jsonp = this.app.enabled('jsonp callback');123124  this.charset = this.charset || 'utf-8';125  this.header('Content-Type', 'application/json');126127  if (callback && jsonp) {128    this.header('Content-Type', 'text/javascript');129    body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';130  }131132  return this.send(body);133};134135/**136 * Set status `code`.137 *138 * @param {Number} code139 * @return {ServerResponse}140 * @api public141 */142143res.status = function(code){144  this.statusCode = code;145  return this;146};147148/**149 * Transfer the file at the given `path`.150 * 151 * Automatically sets the _Content-Type_ response header field.152 * The callback `fn(err)` is invoked when the transfer is complete153 * or when an error occurs. Be sure to check `res.sentHeader`154 * if you wish to attempt responding, as the header and some data155 * may have already been transferred.156 *157 * Options:158 *159 *   - `maxAge` defaulting to 0160 *   - `root`   root directory for relative filenames161 *162 * @param {String} path163 * @param {Object|Function} options or fn164 * @param {Function} fn165 * @api public166 */167168res.sendfile = function(path, options, fn){169  var self = this170    , req = self.req171    , next = this.req.next172    , options = options || {};173174  // support function as second arg175  if ('function' == typeof options) {176    fn = options;177    options = {};178  }179180  // callback181  options.callback = function(err){182    // TODO: remove when node adds this183    self.sentHeader = !! self._header;184185    // error186    if (err) {187      // ditch content-disposition to prevent funky responses188      if (!self.sentHeader) self.removeHeader('Content-Disposition');189190      // not found191      if ('ENOENT' == err.code) return req.next();192193      // lost in limbo if there's no callback194      if (self.sentHeader) return fn && fn(err);195196      // callback available197      if (fn) return fn(err);198199      return req.next(err);200    }201202    fn && fn();203  };204205  // transfer206  options.path = encodeURIComponent(path);207  send(this.req, this, next, options);208};209210/**211 * Transfer the file at the given `path` as an attachment.212 *213 * Optionally providing an alternate attachment `filename`,214 * and optional callback `fn(err)`. The callback is invoked215 * when the data transfer is complete, or when an error has216 * ocurred. Be sure to check `res.sendHeader` if you plan to respond.217 *218 * @param {String} path219 * @param {String|Function} filename or fn220 * @param {Function} fn221 * @api public222 */223224res.download = function(path, filename, fn){225  // support function as second arg226  if ('function' == typeof filename) {227    fn = filename;228    filename = null;229  }230231  return this.attachment(filename || path).sendfile(path, fn);232};233234/**235 * Set _Content-Type_ response header passed through `mime.lookup()`.236 *237 * Examples:238 *239 *     var filename = 'path/to/image.png';240 *     res.contentType(filename);241 *     // res.headers['Content-Type'] is now "image/png"242 *243 *     res.contentType('.html');244 *     res.contentType('html');245 *     res.contentType('json');246 *     res.contentType('png');247 *     res.type('png');248 *249 * @param {String} type250 * @return {ServerResponse} for chaining251 * @api public252 */253254res.contentType =255res.type = function(type){256  return this.header('Content-Type', mime.lookup(type));257};258259/**260 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.261 *262 * @param {String} filename263 * @return {ServerResponse}264 * @api public265 */266267res.attachment = function(filename){268  if (filename) this.contentType(filename);269  this.header('Content-Disposition', filename270    ? 'attachment; filename="' + basename(filename) + '"'271    : 'attachment');272  return this;273};274275/**276 * Set header `field` to `val`, or pass277 * an object of of header fields.278 *279 * Examples:280 *281 *    res.set('Accept', 'application/json');282 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });283 *284 * @param {String|Object} field285 * @param {String} val286 * @return {ServerResponse} for chaining287 * @api public288 */289290res.set = function(field, val){291  if (2 == arguments.length) {292    this.setHeader(field, val);293  } else {294    for (var key in field) {295      this.setHeader(key, field[key]);296    }297  }298  return this;299};300301/**302 * Get value for header `field`.303 *304 * @param {String} field305 * @return {String}306 * @api public307 */308309res.get = function(field){310  return this.getHeader(field);311};312313/**314 * Set or get response header `field` with optional `val`.315 *316 * @param {String} name317 * @param {String} val318 * @return {ServerResponse} for chaining319 * @api public320 */321322res.header = function(field, val){323  if (1 == arguments.length) return this.getHeader(field);324  this.setHeader(field, val);325  return this;326};327328/**329 * Clear cookie `name`.330 *331 * @param {String} name332 * @param {Object} options333 * @param {ServerResponse} for chaining334 * @api public335 */336337res.clearCookie = function(name, options){338  var opts = { expires: new Date(1) };339  return this.cookie(name, '', options340    ? utils.merge(options, opts)341    : opts);342};343344/**345 * Set cookie `name` to `val`, with the given `options`.346 *347 * Options:348 *349 *    - `maxAge`   max-age in milliseconds, converted to `expires`350 *    - `path`     defaults to the "basepath" setting which is typically "/"351 *352 * Examples:353 *354 *    // "Remember Me" for 15 minutes355 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });356 *357 *    // save as above358 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })359 *360 * @param {String} name361 * @param {String} val362 * @param {Options} options363 * @api public364 */365366res.cookie = function(name, val, options){367  options = options || {};368  if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);369  if (undefined === options.path) options.path = this.app.set('basepath');370  var cookie = utils.serializeCookie(name, val, options);371  this.header('Set-Cookie', cookie);372  return this;373};374375/**376 * Redirect to the given `url` with optional response `status`377 * defaulting to 302.378 *379 * The given `url` can also be the name of a mapped url, for380 * example by default express supports "back" which redirects381 * to the _Referrer_ or _Referer_ headers or the application's382 * "basepath" setting. Express also supports "basepath" out of the box,383 * which can be set via `app.set('basepath', '/blog');`.384 *385 * Examples:386 *387 *    res.redirect('/foo/bar');388 *    res.redirect('http://example.com');389 *    res.redirect(301, 'http://example.com');390 *391 * Redirect Mapping:392 * 393 *  To extend the redirect mapping capabilities that Express provides,394 *  we may use the `app.redirect()` method:395 * 396 *     app.redirect('google', 'http://google.com');397 * 398 *  Now in a route we may call:399 *400 *     res.redirect('google');401 *402 *  We may also map dynamic redirects:403 *404 *      app.redirect('comments', function(req, res){405 *          return '/post/' + req.params.id + '/comments';406 *      });407 *408 *  So now we may do the following, and the redirect will dynamically adjust to409 *  the context of the request. If we called this route with _GET /post/12_ our410 *  redirect _Location_ would be _/post/12/comments_.411 *412 *      app.get('/post/:id', function(req, res){413 *        res.redirect('comments');414 *      });415 *416 *  Unless an absolute `url` is given, the app's mount-point417 *  will be respected. For example if we redirect to `/posts`,418 *  and our app is mounted at `/blog` we will redirect to `/blog/posts`.419 *420 * @param {String} url421 * @param {Number} code422 * @api public423 */424425res.redirect = function(url){426  var app = this.app427    , req = this.req428    , base = app.set('basepath') || app.route429    , head = 'HEAD' == req.method430    , status = 302431    , body;432433  // allow status / url434  if (2 == arguments.length) {435    status = url;436    url = arguments[1];437  }438439  // Setup redirect map440  var map = {441      back: req.header('Referrer', base)442    , home: base443  };444445  // Support custom redirect map446  map.__proto__ = app.redirects;447448  // Attempt mapped redirect449  var mapped = 'function' == typeof map[url]450    ? map[url](req, this)451    : map[url];452453  // Perform redirect454  url = mapped || url;455456  // Relative457  if (!~url.indexOf('://')) {458    // Respect mount-point459    if ('/' != base && 0 != url.indexOf(base)) url = base + url;460461    // Absolute462    var host = req.headers.host463      , tls = req.connection.encrypted;464    url = 'http' + (tls ? 's' : '') + '://' + host + url;465  }466467  // Support text/{plain,html} by default468  if (req.accepts('html')) {469    body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';470    this.header('Content-Type', 'text/html');471  } else {472    body = statusCodes[status] + '. Redirecting to ' + url;473    this.header('Content-Type', 'text/plain');474  }475476  // Respond477  this.statusCode = status;478  this.header('Location', url);479  this.end(head ? null : body);480};