response.js
This file
Path
lib/response.js
721 lines · 16.5 KiB · JavaScript
Last changed by
add backwards compat for res.redirect() status. Closes #1336TJ Holowaychukbefore adoption56ffab0
History of this fileTake it
1/**2 * Module dependencies.3 */45var fs = require('fs')6 , http = require('http')7 , path = require('path')8 , connect = require('connect')9 , utils = connect.utils10 , normalizeType = require('./utils').normalizeType11 , normalizeTypes = require('./utils').normalizeTypes12 , etag = require('./utils').etag13 , statusCodes = http.STATUS_CODES14 , send = connect.static.send15 , cookie = require('cookie')16 , send = require('send')17 , crc = require('crc')18 , mime = connect.mime19 , basename = path.basename20 , extname = path.extname21 , join = path.join;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 return this.set('Link', Object.keys(links).map(function(rel){61 return '<' + links[rel] + '>; rel="' + rel + '"';62 }).join(', '));63};6465/**66 * Send a response.67 *68 * Examples:69 *70 * res.send(new Buffer('wahoo'));71 * res.send({ some: 'json' });72 * res.send('<p>some html</p>');73 * res.send(404, 'Sorry, cant find that');74 * res.send(404);75 *76 * @param {Mixed} body or status77 * @param {Mixed} body78 * @return {ServerResponse}79 * @api public80 */8182res.send = function(body){83 var req = this.req84 , head = 'HEAD' == req.method85 , len;8687 // allow status / body88 if (2 == arguments.length) {89 // res.send(body, status) backwards compat90 if ('number' != typeof body && 'number' == typeof arguments[1]) {91 this.statusCode = arguments[1];92 } else {93 this.statusCode = body;94 body = arguments[1];95 }96 }9798 switch (typeof body) {99 // response status100 case 'number':101 this.get('Content-Type') || this.type('txt');102 this.statusCode = body;103 body = http.STATUS_CODES[body];104 break;105 // string defaulting to html106 case 'string':107 if (!this.get('Content-Type')) {108 this.charset = this.charset || 'utf-8';109 this.type('html');110 }111 break;112 case 'boolean':113 case 'object':114 if (null == body) {115 body = '';116 } else if (Buffer.isBuffer(body)) {117 this.get('Content-Type') || this.type('bin');118 } else {119 return this.json(body);120 }121 break;122 }123124 // populate Content-Length125 if (undefined !== body && !this.get('Content-Length')) {126 this.set('Content-Length', len = Buffer.isBuffer(body)127 ? body.length128 : Buffer.byteLength(body));129 }130131 // ETag support132 // TODO: W/ support133 if (len > 1024) {134 if (!this.get('ETag')) {135 this.set('ETag', etag(body));136 }137 }138139 // freshness140 if (req.fresh) this.statusCode = 304;141142 // strip irrelevant headers143 if (204 == this.statusCode || 304 == this.statusCode) {144 this.removeHeader('Content-Type');145 this.removeHeader('Content-Length');146 body = '';147 }148149 // respond150 this.end(head ? null : body);151 return this;152};153154/**155 * Send JSON response.156 *157 * Examples:158 *159 * res.json(null);160 * res.json({ user: 'tj' });161 * res.json(500, 'oh noes!');162 * res.json(404, 'I dont have that');163 *164 * @param {Mixed} obj or status165 * @param {Mixed} obj166 * @return {ServerResponse}167 * @api public168 */169170res.json = function(obj){171 // allow status / body172 if (2 == arguments.length) {173 // res.json(body, status) backwards compat174 if ('number' == typeof arguments[1]) {175 this.statusCode = arguments[1];176 } else {177 this.statusCode = obj;178 obj = arguments[1];179 }180 }181182 // settings183 var app = this.app;184 var replacer = app.get('json replacer');185 var spaces = app.get('json spaces');186 var body = JSON.stringify(obj, replacer, spaces);187188 // content-type189 this.charset = this.charset || 'utf-8';190 this.get('Content-Type') || this.set('Content-Type', 'application/json');191 192 return this.send(body);193};194195/**196 * Send JSON response with JSONP callback support.197 *198 * Examples:199 *200 * res.jsonp(null);201 * res.jsonp({ user: 'tj' });202 * res.jsonp(500, 'oh noes!');203 * res.jsonp(404, 'I dont have that');204 *205 * @param {Mixed} obj or status206 * @param {Mixed} obj207 * @return {ServerResponse}208 * @api public209 */210211res.jsonp = function(obj){212 // allow status / body213 if (2 == arguments.length) {214 // res.json(body, status) backwards compat215 if ('number' == typeof arguments[1]) {216 this.statusCode = arguments[1];217 } else {218 this.statusCode = obj;219 obj = arguments[1];220 }221 }222223 // settings224 var app = this.app;225 var replacer = app.get('json replacer');226 var spaces = app.get('json spaces');227 var body = JSON.stringify(obj, replacer, spaces);228 var callback = this.req.query[app.get('jsonp callback name')];229230 // content-type231 this.charset = this.charset || 'utf-8';232 this.set('Content-Type', 'application/json');233 234 // jsonp235 if (callback) {236 this.set('Content-Type', 'text/javascript');237 body = callback.replace(/[^\[\]\w$.]/g, '') + '(' + body + ');';238 }239240 return this.send(body);241};242243/**244 * Transfer the file at the given `path`.245 * 246 * Automatically sets the _Content-Type_ response header field.247 * The callback `fn(err)` is invoked when the transfer is complete248 * or when an error occurs. Be sure to check `res.sentHeader`249 * if you wish to attempt responding, as the header and some data250 * may have already been transferred.251 *252 * Options:253 *254 * - `maxAge` defaulting to 0255 * - `root` root directory for relative filenames256 *257 * Examples:258 *259 * The following example illustrates how `res.sendfile()` may260 * be used as an alternative for the `static()` middleware for261 * dynamic situations. The code backing `res.sendfile()` is actually262 * the same code, so HTTP cache support etc is identical.263 *264 * app.get('/user/:uid/photos/:file', function(req, res){265 * var uid = req.params.uid266 * , file = req.params.file;267 * 268 * req.user.mayViewFilesFrom(uid, function(yes){269 * if (yes) {270 * res.sendfile('/uploads/' + uid + '/' + file);271 * } else {272 * res.send(403, 'Sorry! you cant see that.');273 * }274 * });275 * });276 *277 * @param {String} path278 * @param {Object|Function} options or fn279 * @param {Function} fn280 * @api public281 */282283res.sendfile = function(path, options, fn){284 var self = this285 , req = self.req286 , next = this.req.next287 , options = options || {}288 , done;289290 // support function as second arg291 if ('function' == typeof options) {292 fn = options;293 options = {};294 }295296 // socket errors297 req.socket.on('error', error);298299 // errors300 function error(err) {301 if (done) return;302 done = true;303304 // clean up305 cleanup();306 if (!self.headerSent) self.removeHeader('Content-Disposition');307308 // callback available309 if (fn) return fn(err);310311 // list in limbo if there's no callback312 if (self.headerSent) return;313314 // delegate315 next(err);316 }317318 // streaming319 function stream() {320 if (done) return;321 cleanup();322 if (fn) self.on('finish', fn);323 }324325 // cleanup326 function cleanup() {327 req.socket.removeListener('error', error);328 }329330 // transfer331 var file = send(req, path);332 if (options.root) file.root(options.root);333 file.maxage(options.maxAge || 0);334 file.on('error', error);335 file.on('directory', next);336 file.on('stream', stream);337 file.pipe(this);338 this.on('finish', cleanup);339};340341/**342 * Transfer the file at the given `path` as an attachment.343 *344 * Optionally providing an alternate attachment `filename`,345 * and optional callback `fn(err)`. The callback is invoked346 * when the data transfer is complete, or when an error has347 * ocurred. Be sure to check `res.headerSent` if you plan to respond.348 *349 * This method uses `res.sendfile()`.350 *351 * @param {String} path352 * @param {String|Function} filename or fn353 * @param {Function} fn354 * @api public355 */356357res.download = function(path, filename, fn){358 // support function as second arg359 if ('function' == typeof filename) {360 fn = filename;361 filename = null;362 }363364 filename = filename || path;365 this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');366 return this.sendfile(path, fn);367};368369/**370 * Set _Content-Type_ response header with `type` through `mime.lookup()`371 * when it does not contain "/", or set the Content-Type to `type` otherwise.372 *373 * Examples:374 *375 * res.type('.html');376 * res.type('html');377 * res.type('json');378 * res.type('application/json');379 * res.type('png');380 *381 * @param {String} type382 * @return {ServerResponse} for chaining383 * @api public384 */385386res.contentType =387res.type = function(type){388 return this.set('Content-Type', ~type.indexOf('/')389 ? type390 : mime.lookup(type));391};392393/**394 * Respond to the Acceptable formats using an `obj`395 * of mime-type callbacks.396 *397 * This method uses `req.accepted`, an array of398 * acceptable types ordered by their quality values.399 * When "Accept" is not present the _first_ callback400 * is invoked, otherwise the first match is used. When401 * no match is performed the server responds with402 * 406 "Not Acceptable".403 *404 * Content-Type is set for you, however if you choose405 * you may alter this within the callback using `res.type()`406 * or `res.set('Content-Type', ...)`.407 *408 * res.format({409 * 'text/plain': function(){410 * res.send('hey');411 * },412 * 413 * 'text/html': function(){414 * res.send('<p>hey</p>');415 * },416 * 417 * 'appliation/json': function(){418 * res.send({ message: 'hey' });419 * }420 * });421 *422 * In addition to canonicalized MIME types you may423 * also use extnames mapped to these types:424 *425 * res.format({426 * text: function(){427 * res.send('hey');428 * },429 * 430 * html: function(){431 * res.send('<p>hey</p>');432 * },433 * 434 * json: function(){435 * res.send({ message: 'hey' });436 * }437 * });438 *439 * By default Express passes an `Error`440 * with a `.status` of 406 to `next(err)`441 * if a match is not made. If you provide442 * a `.default` callback it will be invoked443 * instead.444 *445 * @param {Object} obj446 * @return {ServerResponse} for chaining447 * @api public448 */449450res.format = function(obj){451 var req = this.req452 , next = req.next;453454 var fn = obj.default;455 if (fn) delete obj.default;456 var keys = Object.keys(obj);457458 var key = req.accepts(keys);459460 this.set('Vary', 'Accept');461462 if (key) {463 this.set('Content-Type', normalizeType(key));464 obj[key](req, this, next);465 } else if (fn) {466 fn();467 } else {468 var err = new Error('Not Acceptable');469 err.status = 406;470 err.types = normalizeTypes(keys);471 next(err);472 }473474 return this;475};476477/**478 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.479 *480 * @param {String} filename481 * @return {ServerResponse}482 * @api public483 */484485res.attachment = function(filename){486 if (filename) this.type(extname(filename));487 this.set('Content-Disposition', filename488 ? 'attachment; filename="' + basename(filename) + '"'489 : 'attachment');490 return this;491};492493/**494 * Set header `field` to `val`, or pass495 * an object of header fields.496 *497 * Examples:498 *499 * res.set('Accept', 'application/json');500 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });501 *502 * Aliased as `res.header()`. 503 *504 * @param {String|Object} field505 * @param {String} val506 * @return {ServerResponse} for chaining507 * @api public508 */509510res.set = 511res.header = function(field, val){512 if (2 == arguments.length) {513 this.setHeader(field, '' + val);514 } else {515 for (var key in field) {516 this.setHeader(key, '' + field[key]);517 }518 }519 return this;520};521522/**523 * Get value for header `field`.524 *525 * @param {String} field526 * @return {String}527 * @api public528 */529530res.get = function(field){531 return this.getHeader(field);532};533534/**535 * Clear cookie `name`.536 *537 * @param {String} name538 * @param {Object} options539 * @param {ServerResponse} for chaining540 * @api public541 */542543res.clearCookie = function(name, options){544 var opts = { expires: new Date(1), path: '/' };545 return this.cookie(name, '', options546 ? utils.merge(opts, options)547 : opts);548};549550/**551 * Set cookie `name` to `val`, with the given `options`.552 *553 * Options:554 *555 * - `maxAge` max-age in milliseconds, converted to `expires`556 * - `signed` sign the cookie557 * - `path` defaults to "/"558 *559 * Examples:560 *561 * // "Remember Me" for 15 minutes562 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });563 *564 * // save as above565 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })566 *567 * @param {String} name568 * @param {String|Object} val569 * @param {Options} options570 * @api public571 */572573res.cookie = function(name, val, options){574 options = options || {};575 var secret = this.req.secret;576 var signed = options.signed;577 if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');578 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);579 if (signed) val = 's:' + utils.sign(val, secret);580 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);581 if (null == options.path) options.path = '/';582 this.set('Set-Cookie', cookie.serialize(name, String(val), options));583 return this;584};585586/**587 * Redirect to the given `url` with optional response `status`588 * defaulting to 302.589 *590 * The given `url` can also be the name of a mapped url, for591 * example by default express supports "back" which redirects592 * to the _Referrer_ or _Referer_ headers or "/".593 *594 * Examples:595 *596 * res.redirect('/foo/bar');597 * res.redirect('http://example.com');598 * res.redirect(301, 'http://example.com');599 * res.redirect('http://example.com', 301);600 * res.redirect('../login'); // /blog/post/1 -> /blog/login601 *602 * Mounting:603 *604 * When an application is mounted, and `res.redirect()`605 * is given a path that does _not_ lead with "/". For 606 * example suppose a "blog" app is mounted at "/blog",607 * the following redirect would result in "/blog/login":608 *609 * res.redirect('login');610 *611 * While the leading slash would result in a redirect to "/login":612 *613 * res.redirect('/login');614 *615 * @param {String} url616 * @param {Number} code617 * @api public618 */619620res.redirect = function(url){621 var app = this.app622 , req = this.req623 , head = 'HEAD' == req.method624 , status = 302625 , body;626627 // allow status / url628 if (2 == arguments.length) {629 if ('number' == typeof url) {630 status = url;631 url = arguments[1];632 } else {633 status = arguments[1];634 }635 }636637 // setup redirect map638 var map = { back: req.get('Referrer') || '/' };639640 // perform redirect641 url = map[url] || url;642643 // relative644 if (!~url.indexOf('://') && 0 != url.indexOf('//')) {645 var path = app.path();646647 // relative to path648 if ('.' == url[0]) {649 url = req.path + '/' + url;650 // relative to mount-point651 } else if ('/' != url[0]) {652 url = path + '/' + url;653 }654655 // Absolute656 var host = req.get('Host');657 url = '//' + host + url;658 }659660 // Support text/{plain,html} by default661 this.format({662 text: function(){663 body = statusCodes[status] + '. Redirecting to ' + url;664 },665666 html: function(){667 var u = utils.escape(url);668 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';669 },670671 default: function(){672 body = '';673 }674 });675676 // Respond677 this.statusCode = status;678 this.set('Location', url);679 this.set('Content-Length', Buffer.byteLength(body));680 this.end(head ? null : body);681};682683/**684 * Render `view` with the given `options` and optional callback `fn`.685 * When a callback function is given a response will _not_ be made686 * automatically, otherwise a response of _200_ and _text/html_ is given.687 *688 * Options:689 *690 * - `cache` boolean hinting to the engine it should cache691 * - `filename` filename of the view being rendered692 *693 * @param {String} view694 * @param {Object|Function} options or callback function695 * @param {Function} fn696 * @api public697 */698699res.render = function(view, options, fn){700 var self = this701 , options = options || {}702 , req = this.req703 , app = req.app;704705 // support callback function as second arg706 if ('function' == typeof options) {707 fn = options, options = {};708 }709710 // merge res.locals711 options._locals = self.locals;712713 // default callback to respond714 fn = fn || function(err, str){715 if (err) return req.next(err);716 self.send(str);717 };718719 // render720 app.render(view, options, fn);721};