Skip to content
Myr

response.js

This file

Path

lib/response.js

795 lines · 18.4 KiB · JavaScript

Last changed by

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

History of this file

Take it

1/**2 * Module dependencies.3 */45var deprecate = require('depd')('express');6var escapeHtml = require('escape-html');7var http = require('http');8var path = require('path');9var mixin = require('utils-merge');10var sign = require('cookie-signature').sign;11var normalizeType = require('./utils').normalizeType;12var normalizeTypes = require('./utils').normalizeTypes;13var setCharset = require('./utils').setCharset;14var contentDisposition = require('./utils').contentDisposition;15var statusCodes = http.STATUS_CODES;16var cookie = require('cookie');17var send = require('send');18var basename = path.basename;19var extname = path.extname;20var mime = send.mime;21var vary = require('vary');2223/**24 * Response prototype.25 */2627var res = module.exports = {28  __proto__: http.ServerResponse.prototype29};3031/**32 * Set status `code`.33 *34 * @param {Number} code35 * @return {ServerResponse}36 * @api public37 */3839res.status = function(code){40  this.statusCode = code;41  return this;42};4344/**45 * Set Link header field with the given `links`.46 *47 * Examples:48 *49 *    res.links({50 *      next: 'http://api.example.com/users?page=2',51 *      last: 'http://api.example.com/users?page=5'52 *    });53 *54 * @param {Object} links55 * @return {ServerResponse}56 * @api public57 */5859res.links = function(links){60  var link = this.get('Link') || '';61  if (link) link += ', ';62  return this.set('Link', link + Object.keys(links).map(function(rel){63    return '<' + links[rel] + '>; rel="' + rel + '"';64  }).join(', '));65};6667/**68 * Send a response.69 *70 * Examples:71 *72 *     res.send(new Buffer('wahoo'));73 *     res.send({ some: 'json' });74 *     res.send('<p>some html</p>');75 *     res.send(404, 'Sorry, cant find that');76 *     res.send(404);77 *78 * @api public79 */8081res.send = function(body){82  var req = this.req;83  var head = 'HEAD' == req.method;84  var type;85  var encoding;86  var len;8788  // settings89  var app = this.app;9091  // allow status / body92  if (2 == arguments.length) {93    // res.send(body, status) backwards compat94    if ('number' != typeof body && 'number' == typeof arguments[1]) {95      deprecate('res.send(body, status): Use res.send(status, body) instead');96      this.statusCode = arguments[1];97    } else {98      this.statusCode = body;99      body = arguments[1];100    }101  }102103  switch (typeof body) {104    // response status105    case 'number':106      this.get('Content-Type') || this.type('txt');107      this.statusCode = body;108      body = http.STATUS_CODES[body];109      break;110    // string defaulting to html111    case 'string':112      if (!this.get('Content-Type')) this.type('html');113      break;114    case 'boolean':115    case 'object':116      if (null == body) {117        body = '';118      } else if (Buffer.isBuffer(body)) {119        this.get('Content-Type') || this.type('bin');120      } else {121        return this.json(body);122      }123      break;124  }125126  // write strings in utf-8127  if ('string' === typeof body) {128    encoding = 'utf8';129    type = this.get('Content-Type');130131    // reflect this in content-type132    if ('string' === typeof type) {133      this.set('Content-Type', setCharset(type, 'utf-8'));134    }135  }136137  // populate Content-Length138  if (undefined !== body && !this.get('Content-Length')) {139    len = Buffer.isBuffer(body)140      ? body.length141      : Buffer.byteLength(body, encoding);142    this.set('Content-Length', len);143  }144145  // ETag support146  var etag = len !== undefined && app.get('etag fn');147  if (etag && ('GET' === req.method || 'HEAD' === req.method)) {148    if (!this.get('ETag')) {149      etag = etag(body, encoding);150      etag && this.set('ETag', etag);151    }152  }153154  // freshness155  if (req.fresh) this.statusCode = 304;156157  // strip irrelevant headers158  if (204 == this.statusCode || 304 == this.statusCode) {159    this.removeHeader('Content-Type');160    this.removeHeader('Content-Length');161    this.removeHeader('Transfer-Encoding');162    body = '';163  }164165  // respond166  this.end((head ? null : body), encoding);167168  return this;169};170171/**172 * Send JSON response.173 *174 * Examples:175 *176 *     res.json(null);177 *     res.json({ user: 'tj' });178 *     res.json(500, 'oh noes!');179 *     res.json(404, 'I dont have that');180 *181 * @api public182 */183184res.json = function(obj){185  // allow status / body186  if (2 == arguments.length) {187    // res.json(body, status) backwards compat188    if ('number' == typeof arguments[1]) {189      this.statusCode = arguments[1];190      if (typeof obj === 'number') {191        deprecate('res.json(obj, status): Use res.json(status, obj) instead');192      } else {193        deprecate('res.json(num, status): Use res.status(status).json(num) instead');194      }195    } else {196      this.statusCode = obj;197      obj = arguments[1];198    }199  }200201  // settings202  var app = this.app;203  var replacer = app.get('json replacer');204  var spaces = app.get('json spaces');205  var body = JSON.stringify(obj, replacer, spaces);206207  // content-type208  this.get('Content-Type') || this.set('Content-Type', 'application/json');209210  return this.send(body);211};212213/**214 * Send JSON response with JSONP callback support.215 *216 * Examples:217 *218 *     res.jsonp(null);219 *     res.jsonp({ user: 'tj' });220 *     res.jsonp(500, 'oh noes!');221 *     res.jsonp(404, 'I dont have that');222 *223 * @api public224 */225226res.jsonp = function(obj){227  // allow status / body228  if (2 == arguments.length) {229    // res.json(body, status) backwards compat230    if ('number' == typeof arguments[1]) {231      this.statusCode = arguments[1];232      if (typeof obj === 'number') {233        deprecate('res.jsonp(obj, status): Use res.jsonp(status, obj) instead');234      } else {235        deprecate('res.jsonp(num, status): Use res.status(status).jsonp(num) instead');236      }237    } else {238      this.statusCode = obj;239      obj = arguments[1];240    }241  }242243  // settings244  var app = this.app;245  var replacer = app.get('json replacer');246  var spaces = app.get('json spaces');247  var body = JSON.stringify(obj, replacer, spaces)248    .replace(/\u2028/g, '\\u2028')249    .replace(/\u2029/g, '\\u2029');250  var callback = this.req.query[app.get('jsonp callback name')];251252  // content-type253  this.get('Content-Type') || this.set('Content-Type', 'application/json');254255  // fixup callback256  if (Array.isArray(callback)) {257    callback = callback[0];258  }259260  // jsonp261  if (callback && 'string' === typeof callback) {262    this.set('Content-Type', 'text/javascript');263    var cb = callback.replace(/[^\[\]\w$.]/g, '');264    body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';265  }266267  return this.send(body);268};269270/**271 * Transfer the file at the given `path`.272 *273 * Automatically sets the _Content-Type_ response header field.274 * The callback `fn(err)` is invoked when the transfer is complete275 * or when an error occurs. Be sure to check `res.sentHeader`276 * if you wish to attempt responding, as the header and some data277 * may have already been transferred.278 *279 * Options:280 *281 *   - `maxAge`  defaulting to 0 (can be string converted by `ms`)282 *   - `root`    root directory for relative filenames283 *   - `headers` object of headers to serve with file284 *   - `hidden`  serve hidden files, defaulting to false285 *286 * Other options are passed along to `send`.287 *288 * Examples:289 *290 *  The following example illustrates how `res.sendfile()` may291 *  be used as an alternative for the `static()` middleware for292 *  dynamic situations. The code backing `res.sendfile()` is actually293 *  the same code, so HTTP cache support etc is identical.294 *295 *     app.get('/user/:uid/photos/:file', function(req, res){296 *       var uid = req.params.uid297 *         , file = req.params.file;298 *299 *       req.user.mayViewFilesFrom(uid, function(yes){300 *         if (yes) {301 *           res.sendfile('/uploads/' + uid + '/' + file);302 *         } else {303 *           res.send(403, 'Sorry! you cant see that.');304 *         }305 *       });306 *     });307 *308 * @api public309 */310311res.sendfile = function(path, options, fn){312  options = options || {};313  var self = this;314  var req = self.req;315  var next = this.req.next;316  var done;317318319  // support function as second arg320  if ('function' == typeof options) {321    fn = options;322    options = {};323  }324325  // socket errors326  req.socket.on('error', error);327328  // errors329  function error(err) {330    if (done) return;331    done = true;332333    // clean up334    cleanup();335336    // callback available337    if (fn) return fn(err);338339    // delegate340    next(err);341  }342343  // streaming344  function stream(stream) {345    if (done) return;346    cleanup();347    if (fn) stream.on('end', fn);348  }349350  // cleanup351  function cleanup() {352    req.socket.removeListener('error', error);353  }354355  // Back-compat356  options.maxage = options.maxage || options.maxAge || 0;357358  // transfer359  var file = send(req, path, options);360  file.on('error', error);361  file.on('directory', next);362  file.on('stream', stream);363364  if (options.headers) {365    // set headers on successful transfer366    file.on('headers', function headers(res) {367      var obj = options.headers;368      var keys = Object.keys(obj);369370      for (var i = 0; i < keys.length; i++) {371        var k = keys[i];372        res.setHeader(k, obj[k]);373      }374    });375  }376377  // pipe378  file.pipe(this);379  this.on('finish', cleanup);380};381382/**383 * Transfer the file at the given `path` as an attachment.384 *385 * Optionally providing an alternate attachment `filename`,386 * and optional callback `fn(err)`. The callback is invoked387 * when the data transfer is complete, or when an error has388 * ocurred. Be sure to check `res.headersSent` if you plan to respond.389 *390 * This method uses `res.sendfile()`.391 *392 * @api public393 */394395res.download = function(path, filename, fn){396  // support function as second arg397  if ('function' == typeof filename) {398    fn = filename;399    filename = null;400  }401402  filename = filename || path;403404  // set Content-Disposition when file is sent405  var headers = {406    'Content-Disposition': contentDisposition(filename)407  };408409  return this.sendfile(path, { headers: headers }, fn);410};411412/**413 * Set _Content-Type_ response header with `type` through `mime.lookup()`414 * when it does not contain "/", or set the Content-Type to `type` otherwise.415 *416 * Examples:417 *418 *     res.type('.html');419 *     res.type('html');420 *     res.type('json');421 *     res.type('application/json');422 *     res.type('png');423 *424 * @param {String} type425 * @return {ServerResponse} for chaining426 * @api public427 */428429res.contentType =430res.type = function(type){431  return this.set('Content-Type', ~type.indexOf('/')432    ? type433    : mime.lookup(type));434};435436/**437 * Respond to the Acceptable formats using an `obj`438 * of mime-type callbacks.439 *440 * This method uses `req.accepted`, an array of441 * acceptable types ordered by their quality values.442 * When "Accept" is not present the _first_ callback443 * is invoked, otherwise the first match is used. When444 * no match is performed the server responds with445 * 406 "Not Acceptable".446 *447 * Content-Type is set for you, however if you choose448 * you may alter this within the callback using `res.type()`449 * or `res.set('Content-Type', ...)`.450 *451 *    res.format({452 *      'text/plain': function(){453 *        res.send('hey');454 *      },455 *456 *      'text/html': function(){457 *        res.send('<p>hey</p>');458 *      },459 *460 *      'appliation/json': function(){461 *        res.send({ message: 'hey' });462 *      }463 *    });464 *465 * In addition to canonicalized MIME types you may466 * also use extnames mapped to these types:467 *468 *    res.format({469 *      text: function(){470 *        res.send('hey');471 *      },472 *473 *      html: function(){474 *        res.send('<p>hey</p>');475 *      },476 *477 *      json: function(){478 *        res.send({ message: 'hey' });479 *      }480 *    });481 *482 * By default Express passes an `Error`483 * with a `.status` of 406 to `next(err)`484 * if a match is not made. If you provide485 * a `.default` callback it will be invoked486 * instead.487 *488 * @param {Object} obj489 * @return {ServerResponse} for chaining490 * @api public491 */492493res.format = function(obj){494  var req = this.req;495  var next = req.next;496497  var fn = obj.default;498  if (fn) delete obj.default;499  var keys = Object.keys(obj);500501  var key = req.accepts(keys);502503  this.vary("Accept");504505  if (key) {506    this.set('Content-Type', normalizeType(key).value);507    obj[key](req, this, next);508  } else if (fn) {509    fn();510  } else {511    var err = new Error('Not Acceptable');512    err.status = 406;513    err.types = normalizeTypes(keys).map(function(o){ return o.value });514    next(err);515  }516517  return this;518};519520/**521 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.522 *523 * @param {String} filename524 * @return {ServerResponse}525 * @api public526 */527528res.attachment = function(filename){529  if (filename) this.type(extname(filename));530  this.set('Content-Disposition', contentDisposition(filename));531  return this;532};533534/**535 * Set header `field` to `val`, or pass536 * an object of header fields.537 *538 * Examples:539 *540 *    res.set('Foo', ['bar', 'baz']);541 *    res.set('Accept', 'application/json');542 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });543 *544 * Aliased as `res.header()`.545 *546 * @param {String|Object|Array} field547 * @param {String} val548 * @return {ServerResponse} for chaining549 * @api public550 */551552res.set =553res.header = function(field, val){554  if (2 == arguments.length) {555    if (Array.isArray(val)) val = val.map(String);556    else val = String(val);557    if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {558      var charset = mime.charsets.lookup(val.split(';')[0]);559      if (charset) val += '; charset=' + charset.toLowerCase();560    }561    this.setHeader(field, val);562  } else {563    for (var key in field) {564      this.set(key, field[key]);565    }566  }567  return this;568};569570/**571 * Get value for header `field`.572 *573 * @param {String} field574 * @return {String}575 * @api public576 */577578res.get = function(field){579  return this.getHeader(field);580};581582/**583 * Clear cookie `name`.584 *585 * @param {String} name586 * @param {Object} options587 * @param {ServerResponse} for chaining588 * @api public589 */590591res.clearCookie = function(name, options){592  var opts = { expires: new Date(1), path: '/' };593  return this.cookie(name, '', options594    ? mixin(opts, options)595    : opts);596};597598/**599 * Set cookie `name` to `val`, with the given `options`.600 *601 * Options:602 *603 *    - `maxAge`   max-age in milliseconds, converted to `expires`604 *    - `signed`   sign the cookie605 *    - `path`     defaults to "/"606 *607 * Examples:608 *609 *    // "Remember Me" for 15 minutes610 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });611 *612 *    // save as above613 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })614 *615 * @param {String} name616 * @param {String|Object} val617 * @param {Options} options618 * @api public619 */620621res.cookie = function(name, val, options){622  options = mixin({}, options);623  var secret = this.req.secret;624  var signed = options.signed;625  if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');626  if ('number' == typeof val) val = val.toString();627  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);628  if (signed) val = 's:' + sign(val, secret);629  if ('maxAge' in options) {630    options.expires = new Date(Date.now() + options.maxAge);631    options.maxAge /= 1000;632  }633  if (null == options.path) options.path = '/';634  var headerVal = cookie.serialize(name, String(val), options);635636  // supports multiple 'res.cookie' calls by getting previous value637  var prev = this.get('Set-Cookie');638  if (prev) {639    if (Array.isArray(prev)) {640      headerVal = prev.concat(headerVal);641    } else {642      headerVal = [prev, headerVal];643    }644  }645  this.set('Set-Cookie', headerVal);646  return this;647};648649650/**651 * Set the location header to `url`.652 *653 * The given `url` can also be "back", which redirects654 * to the _Referrer_ or _Referer_ headers or "/".655 *656 * Examples:657 *658 *    res.location('/foo/bar').;659 *    res.location('http://example.com');660 *    res.location('../login');661 *662 * @param {String} url663 * @api public664 */665666res.location = function(url){667  var req = this.req;668669  // "back" is an alias for the referrer670  if ('back' == url) url = req.get('Referrer') || '/';671672  // Respond673  this.set('Location', url);674  return this;675};676677/**678 * Redirect to the given `url` with optional response `status`679 * defaulting to 302.680 *681 * The resulting `url` is determined by `res.location()`, so682 * it will play nicely with mounted apps, relative paths,683 * `"back"` etc.684 *685 * Examples:686 *687 *    res.redirect('/foo/bar');688 *    res.redirect('http://example.com');689 *    res.redirect(301, 'http://example.com');690 *    res.redirect('http://example.com', 301);691 *    res.redirect('../login'); // /blog/post/1 -> /blog/login692 *693 * @param {String} url694 * @param {Number} code695 * @api public696 */697698res.redirect = function(url){699  var head = 'HEAD' == this.req.method;700  var status = 302;701  var body;702703  // allow status / url704  if (2 == arguments.length) {705    if ('number' == typeof url) {706      status = url;707      url = arguments[1];708    } else {709      status = arguments[1];710    }711  }712713  // Set location header714  this.location(url);715  url = this.get('Location');716717  // Support text/{plain,html} by default718  this.format({719    text: function(){720      body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);721    },722723    html: function(){724      var u = escapeHtml(url);725      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';726    },727728    default: function(){729      body = '';730    }731  });732733  // Respond734  this.statusCode = status;735  this.set('Content-Length', Buffer.byteLength(body));736  this.end(head ? null : body);737};738739/**740 * Add `field` to Vary. If already present in the Vary set, then741 * this call is simply ignored.742 *743 * @param {Array|String} field744 * @param {ServerResponse} for chaining745 * @api public746 */747748res.vary = function(field){749  // checks for back-compat750  if (!field || (Array.isArray(field) && !field.length)) {751    deprecate('res.vary(): Provide a field name');752    return this;753  }754755  vary(this, field);756757  return this;758};759760/**761 * Render `view` with the given `options` and optional callback `fn`.762 * When a callback function is given a response will _not_ be made763 * automatically, otherwise a response of _200_ and _text/html_ is given.764 *765 * Options:766 *767 *  - `cache`     boolean hinting to the engine it should cache768 *  - `filename`  filename of the view being rendered769 *770 * @api public771 */772773res.render = function(view, options, fn){774  options = options || {};775  var self = this;776  var req = this.req;777  var app = req.app;778779  // support callback function as second arg780  if ('function' == typeof options) {781    fn = options, options = {};782  }783784  // merge res.locals785  options._locals = self.locals;786787  // default callback to respond788  fn = fn || function(err, str){789    if (err) return req.next(err);790    self.send(str);791  };792793  // render794  app.render(view, options, fn);795};