response.js
This file
Path
lib/response.js
717 lines · 16.4 KiB · JavaScript
Last changed by
fix cookie max-ageTJ Holowaychukbefore adoptionab9c275
History of this fileTake it
1/**2 * Module dependencies.3 */45var http = require('http')6 , path = require('path')7 , connect = require('connect')8 , utils = connect.utils9 , sign = require('cookie-signature').sign10 , normalizeType = require('./utils').normalizeType11 , normalizeTypes = require('./utils').normalizeTypes12 , etag = require('./utils').etag13 , statusCodes = http.STATUS_CODES14 , cookie = require('cookie')15 , send = require('send')16 , mime = connect.mime17 , basename = path.basename18 , extname = path.extname19 , join = path.join;2021/**22 * Response prototype.23 */2425var res = module.exports = {26 __proto__: http.ServerResponse.prototype27};2829/**30 * Set status `code`.31 *32 * @param {Number} code33 * @return {ServerResponse}34 * @api public35 */3637res.status = function(code){38 this.statusCode = code;39 return this;40};4142/**43 * Set Link header field with the given `links`.44 *45 * Examples:46 *47 * res.links({48 * next: 'http://api.example.com/users?page=2',49 * last: 'http://api.example.com/users?page=5'50 * });51 *52 * @param {Object} links53 * @return {ServerResponse}54 * @api public55 */5657res.links = function(links){58 return this.set('Link', Object.keys(links).map(function(rel){59 return '<' + links[rel] + '>; rel="' + rel + '"';60 }).join(', '));61};6263/**64 * Send a response.65 *66 * Examples:67 *68 * res.send(new Buffer('wahoo'));69 * res.send({ some: 'json' });70 * res.send('<p>some html</p>');71 * res.send(404, 'Sorry, cant find that');72 * res.send(404);73 *74 * @param {Mixed} body or status75 * @param {Mixed} body76 * @return {ServerResponse}77 * @api public78 */7980res.send = function(body){81 var req = this.req82 , head = 'HEAD' == req.method83 , len;8485 // allow status / body86 if (2 == arguments.length) {87 // res.send(body, status) backwards compat88 if ('number' != typeof body && 'number' == typeof arguments[1]) {89 this.statusCode = arguments[1];90 } else {91 this.statusCode = body;92 body = arguments[1];93 }94 }9596 switch (typeof body) {97 // response status98 case 'number':99 this.get('Content-Type') || this.type('txt');100 this.statusCode = body;101 body = http.STATUS_CODES[body];102 break;103 // string defaulting to html104 case 'string':105 if (!this.get('Content-Type')) {106 this.charset = this.charset || 'utf-8';107 this.type('html');108 }109 break;110 case 'boolean':111 case 'object':112 if (null == body) {113 body = '';114 } else if (Buffer.isBuffer(body)) {115 this.get('Content-Type') || this.type('bin');116 } else {117 return this.json(body);118 }119 break;120 }121122 // populate Content-Length123 if (undefined !== body && !this.get('Content-Length')) {124 this.set('Content-Length', len = Buffer.isBuffer(body)125 ? body.length126 : Buffer.byteLength(body));127 }128129 // ETag support130 // TODO: W/ support131 if (len > 1024) {132 if (!this.get('ETag')) {133 this.set('ETag', etag(body));134 }135 }136137 // freshness138 if (req.fresh) this.statusCode = 304;139140 // strip irrelevant headers141 if (204 == this.statusCode || 304 == this.statusCode) {142 this.removeHeader('Content-Type');143 this.removeHeader('Content-Length');144 body = '';145 }146147 // respond148 this.end(head ? null : body);149 return this;150};151152/**153 * Send JSON response.154 *155 * Examples:156 *157 * res.json(null);158 * res.json({ user: 'tj' });159 * res.json(500, 'oh noes!');160 * res.json(404, 'I dont have that');161 *162 * @param {Mixed} obj or status163 * @param {Mixed} obj164 * @return {ServerResponse}165 * @api public166 */167168res.json = function(obj){169 // allow status / body170 if (2 == arguments.length) {171 // res.json(body, status) backwards compat172 if ('number' == typeof arguments[1]) {173 this.statusCode = arguments[1];174 } else {175 this.statusCode = obj;176 obj = arguments[1];177 }178 }179180 // settings181 var app = this.app;182 var replacer = app.get('json replacer');183 var spaces = app.get('json spaces');184 var body = JSON.stringify(obj, replacer, spaces);185186 // content-type187 this.charset = this.charset || 'utf-8';188 this.get('Content-Type') || this.set('Content-Type', 'application/json');189 190 return this.send(body);191};192193/**194 * Send JSON response with JSONP callback support.195 *196 * Examples:197 *198 * res.jsonp(null);199 * res.jsonp({ user: 'tj' });200 * res.jsonp(500, 'oh noes!');201 * res.jsonp(404, 'I dont have that');202 *203 * @param {Mixed} obj or status204 * @param {Mixed} obj205 * @return {ServerResponse}206 * @api public207 */208209res.jsonp = function(obj){210 // allow status / body211 if (2 == arguments.length) {212 // res.json(body, status) backwards compat213 if ('number' == typeof arguments[1]) {214 this.statusCode = arguments[1];215 } else {216 this.statusCode = obj;217 obj = arguments[1];218 }219 }220221 // settings222 var app = this.app;223 var replacer = app.get('json replacer');224 var spaces = app.get('json spaces');225 var body = JSON.stringify(obj, replacer, spaces);226 var callback = this.req.query[app.get('jsonp callback name')];227228 // content-type229 this.charset = this.charset || 'utf-8';230 this.set('Content-Type', 'application/json');231 232 // jsonp233 if (callback) {234 this.set('Content-Type', 'text/javascript');235 var cb = callback.replace(/[^\[\]\w$.]/g, '');236 body = cb + ' && ' + cb + '(' + body + ');';237 }238239 return this.send(body);240};241242/**243 * Transfer the file at the given `path`.244 * 245 * Automatically sets the _Content-Type_ response header field.246 * The callback `fn(err)` is invoked when the transfer is complete247 * or when an error occurs. Be sure to check `res.sentHeader`248 * if you wish to attempt responding, as the header and some data249 * may have already been transferred.250 *251 * Options:252 *253 * - `maxAge` defaulting to 0254 * - `root` root directory for relative filenames255 *256 * Examples:257 *258 * The following example illustrates how `res.sendfile()` may259 * be used as an alternative for the `static()` middleware for260 * dynamic situations. The code backing `res.sendfile()` is actually261 * the same code, so HTTP cache support etc is identical.262 *263 * app.get('/user/:uid/photos/:file', function(req, res){264 * var uid = req.params.uid265 * , file = req.params.file;266 * 267 * req.user.mayViewFilesFrom(uid, function(yes){268 * if (yes) {269 * res.sendfile('/uploads/' + uid + '/' + file);270 * } else {271 * res.send(403, 'Sorry! you cant see that.');272 * }273 * });274 * });275 *276 * @param {String} path277 * @param {Object|Function} options or fn278 * @param {Function} fn279 * @api public280 */281282res.sendfile = function(path, options, fn){283 var self = this284 , req = self.req285 , next = this.req.next286 , options = options || {}287 , done;288289 // support function as second arg290 if ('function' == typeof options) {291 fn = options;292 options = {};293 }294295 // socket errors296 req.socket.on('error', error);297298 // errors299 function error(err) {300 if (done) return;301 done = true;302303 // clean up304 cleanup();305 if (!self.headerSent) self.removeHeader('Content-Disposition');306307 // callback available308 if (fn) return fn(err);309310 // list in limbo if there's no callback311 if (self.headerSent) return;312313 // delegate314 next(err);315 }316317 // streaming318 function stream() {319 if (done) return;320 cleanup();321 if (fn) self.on('finish', fn);322 }323324 // cleanup325 function cleanup() {326 req.socket.removeListener('error', error);327 }328329 // transfer330 var file = send(req, path);331 if (options.root) file.root(options.root);332 file.maxage(options.maxAge || 0);333 file.on('error', error);334 file.on('directory', next);335 file.on('stream', stream);336 file.pipe(this);337 this.on('finish', cleanup);338};339340/**341 * Transfer the file at the given `path` as an attachment.342 *343 * Optionally providing an alternate attachment `filename`,344 * and optional callback `fn(err)`. The callback is invoked345 * when the data transfer is complete, or when an error has346 * ocurred. Be sure to check `res.headerSent` if you plan to respond.347 *348 * This method uses `res.sendfile()`.349 *350 * @param {String} path351 * @param {String|Function} filename or fn352 * @param {Function} fn353 * @api public354 */355356res.download = function(path, filename, fn){357 // support function as second arg358 if ('function' == typeof filename) {359 fn = filename;360 filename = null;361 }362363 filename = filename || path;364 this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');365 return this.sendfile(path, fn);366};367368/**369 * Set _Content-Type_ response header with `type` through `mime.lookup()`370 * when it does not contain "/", or set the Content-Type to `type` otherwise.371 *372 * Examples:373 *374 * res.type('.html');375 * res.type('html');376 * res.type('json');377 * res.type('application/json');378 * res.type('png');379 *380 * @param {String} type381 * @return {ServerResponse} for chaining382 * @api public383 */384385res.contentType =386res.type = function(type){387 return this.set('Content-Type', ~type.indexOf('/')388 ? type389 : mime.lookup(type));390};391392/**393 * Respond to the Acceptable formats using an `obj`394 * of mime-type callbacks.395 *396 * This method uses `req.accepted`, an array of397 * acceptable types ordered by their quality values.398 * When "Accept" is not present the _first_ callback399 * is invoked, otherwise the first match is used. When400 * no match is performed the server responds with401 * 406 "Not Acceptable".402 *403 * Content-Type is set for you, however if you choose404 * you may alter this within the callback using `res.type()`405 * or `res.set('Content-Type', ...)`.406 *407 * res.format({408 * 'text/plain': function(){409 * res.send('hey');410 * },411 * 412 * 'text/html': function(){413 * res.send('<p>hey</p>');414 * },415 * 416 * 'appliation/json': function(){417 * res.send({ message: 'hey' });418 * }419 * });420 *421 * In addition to canonicalized MIME types you may422 * also use extnames mapped to these types:423 *424 * res.format({425 * text: function(){426 * res.send('hey');427 * },428 * 429 * html: function(){430 * res.send('<p>hey</p>');431 * },432 * 433 * json: function(){434 * res.send({ message: 'hey' });435 * }436 * });437 *438 * By default Express passes an `Error`439 * with a `.status` of 406 to `next(err)`440 * if a match is not made. If you provide441 * a `.default` callback it will be invoked442 * instead.443 *444 * @param {Object} obj445 * @return {ServerResponse} for chaining446 * @api public447 */448449res.format = function(obj){450 var req = this.req451 , next = req.next;452453 var fn = obj.default;454 if (fn) delete obj.default;455 var keys = Object.keys(obj);456457 var key = req.accepts(keys);458459 this.set('Vary', 'Accept');460461 if (key) {462 this.set('Content-Type', normalizeType(key));463 obj[key](req, this, next);464 } else if (fn) {465 fn();466 } else {467 var err = new Error('Not Acceptable');468 err.status = 406;469 err.types = normalizeTypes(keys);470 next(err);471 }472473 return this;474};475476/**477 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.478 *479 * @param {String} filename480 * @return {ServerResponse}481 * @api public482 */483484res.attachment = function(filename){485 if (filename) this.type(extname(filename));486 this.set('Content-Disposition', filename487 ? 'attachment; filename="' + basename(filename) + '"'488 : 'attachment');489 return this;490};491492/**493 * Set header `field` to `val`, or pass494 * an object of header fields.495 *496 * Examples:497 *498 * res.set('Accept', 'application/json');499 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });500 *501 * Aliased as `res.header()`. 502 *503 * @param {String|Object} field504 * @param {String} val505 * @return {ServerResponse} for chaining506 * @api public507 */508509res.set = 510res.header = function(field, val){511 if (2 == arguments.length) {512 this.setHeader(field, '' + val);513 } else {514 for (var key in field) {515 this.setHeader(key, '' + field[key]);516 }517 }518 return this;519};520521/**522 * Get value for header `field`.523 *524 * @param {String} field525 * @return {String}526 * @api public527 */528529res.get = function(field){530 return this.getHeader(field);531};532533/**534 * Clear cookie `name`.535 *536 * @param {String} name537 * @param {Object} options538 * @param {ServerResponse} for chaining539 * @api public540 */541542res.clearCookie = function(name, options){543 var opts = { expires: new Date(1), path: '/' };544 return this.cookie(name, '', options545 ? utils.merge(opts, options)546 : opts);547};548549/**550 * Set cookie `name` to `val`, with the given `options`.551 *552 * Options:553 *554 * - `maxAge` max-age in milliseconds, converted to `expires`555 * - `signed` sign the cookie556 * - `path` defaults to "/"557 *558 * Examples:559 *560 * // "Remember Me" for 15 minutes561 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });562 *563 * // save as above564 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })565 *566 * @param {String} name567 * @param {String|Object} val568 * @param {Options} options569 * @api public570 */571572res.cookie = function(name, val, options){573 options = options || {};574 var secret = this.req.secret;575 var signed = options.signed;576 if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');577 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);578 if (signed) val = 's:' + sign(val, secret);579 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);580 if (null == options.path) options.path = '/';581 options.maxAge /= 1000;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 }654 }655656 // Support text/{plain,html} by default657 this.format({658 text: function(){659 body = statusCodes[status] + '. Redirecting to ' + url;660 },661662 html: function(){663 var u = utils.escape(url);664 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';665 },666667 default: function(){668 body = '';669 }670 });671672 // Respond673 this.statusCode = status;674 this.set('Location', url);675 this.set('Content-Length', Buffer.byteLength(body));676 this.end(head ? null : body);677};678679/**680 * Render `view` with the given `options` and optional callback `fn`.681 * When a callback function is given a response will _not_ be made682 * automatically, otherwise a response of _200_ and _text/html_ is given.683 *684 * Options:685 *686 * - `cache` boolean hinting to the engine it should cache687 * - `filename` filename of the view being rendered688 *689 * @param {String} view690 * @param {Object|Function} options or callback function691 * @param {Function} fn692 * @api public693 */694695res.render = function(view, options, fn){696 var self = this697 , options = options || {}698 , req = this.req699 , app = req.app;700701 // support callback function as second arg702 if ('function' == typeof options) {703 fn = options, options = {};704 }705706 // merge res.locals707 options._locals = self.locals;708709 // default callback to respond710 fn = fn || function(err, str){711 if (err) return req.next(err);712 self.send(str);713 };714715 // render716 app.render(view, options, fn);717};