response.js
This file
Path
lib/response.js
596 lines · 13.7 KiB · JavaScript
Last changed by
refactoringTj Holowaychukbefore adoptionf961022
History of this fileTake 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 , send = connect.static.send19 , mime = require('mime')20 , basename = path.basename21 , 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 Cache-Control to the given `type` and `options`.46 *47 * Options:48 *49 * - `maxAge` in milliseconds50 *51 * @param {String} type52 * @param {Object} options53 * @return {ServerResponse}54 * @api public55 */5657res.cache = function(type, options){58 var val = type;59 options = options || {};60 if (options.maxAge) val += ', max-age=' + (options.maxAge / 1000); 61 return this.set('Cache-Control', val);62};6364/**65 * Send a response.66 *67 * Examples:68 *69 * res.send(new Buffer('wahoo'));70 * res.send({ some: 'json' });71 * res.send('<p>some html</p>');72 * res.send(404, 'Sorry, cant find that');73 * res.send(404);74 *75 * @param {Mixed} body or status76 * @param {Mixed} body77 * @return {ServerResponse}78 * @api public79 */8081res.send = function(body){82 var req = this.req83 , head = 'HEAD' == req.method;8485 // allow status / body86 if (2 == arguments.length) {87 this.statusCode = body;88 body = arguments[1];89 }9091 switch (typeof body) {92 // response status93 case 'number':94 this.header('Content-Type') || this.contentType('.txt');95 this.statusCode = body;96 body = http.STATUS_CODES[body];97 break;98 // string defaulting to html99 case 'string':100 if (!this.header('Content-Type')) {101 this.charset = this.charset || 'utf-8';102 this.contentType('.html');103 }104 break;105 case 'boolean':106 case 'object':107 if (null == body) {108 body = '';109 } else if (Buffer.isBuffer(body)) {110 this.header('Content-Type') || this.contentType('.bin');111 } else {112 return this.json(body);113 }114 break;115 }116117 // populate Content-Length118 if (undefined !== body && !this.header('Content-Length')) {119 this.header('Content-Length', Buffer.isBuffer(body)120 ? body.length121 : Buffer.byteLength(body));122 }123124 // strip irrelevant headers125 if (204 == this.statusCode || 304 == this.statusCode) {126 this.removeHeader('Content-Type');127 this.removeHeader('Content-Length');128 body = '';129 }130131 // respond132 this.end(head ? null : body);133 return this;134};135136/**137 * Send JSON response.138 *139 * Examples:140 *141 * res.json(null);142 * res.json({ user: 'tj' });143 * res.json(500, 'oh noes!');144 * res.json(404, 'I dont have that');145 *146 * @param {Mixed} obj or status147 * @param {Mixed} obj148 * @return {ServerResponse}149 * @api public150 */151152res.json = function(obj){153 // allow status / body154 if (2 == arguments.length) {155 this.statusCode = obj;156 obj = arguments[1];157 }158159 var body = JSON.stringify(obj)160 , callback = this.req.query.callback161 , jsonp = this.app.enabled('jsonp callback');162163 this.charset = this.charset || 'utf-8';164 this.header('Content-Type', 'application/json');165166 if (callback && jsonp) {167 this.header('Content-Type', 'text/javascript');168 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';169 }170171 return this.send(body);172};173174/**175 * Transfer the file at the given `path`.176 * 177 * Automatically sets the _Content-Type_ response header field.178 * The callback `fn(err)` is invoked when the transfer is complete179 * or when an error occurs. Be sure to check `res.sentHeader`180 * if you wish to attempt responding, as the header and some data181 * may have already been transferred.182 *183 * Options:184 *185 * - `maxAge` defaulting to 0186 * - `root` root directory for relative filenames187 *188 * @param {String} path189 * @param {Object|Function} options or fn190 * @param {Function} fn191 * @api public192 */193194res.sendfile = function(path, options, fn){195 var self = this196 , req = self.req197 , next = this.req.next198 , options = options || {};199200 // support function as second arg201 if ('function' == typeof options) {202 fn = options;203 options = {};204 }205206 // callback207 options.callback = function(err){208 if (err) {209 // cast ENOENT210 if ('ENOENT' == err.code) err = 404;211212 // coerce numeric error to an Error213 if ('number' == typeof err) err = utils.error(err);214215 // ditch content-disposition to prevent funky responses216 if (!self.headerSent) self.removeHeader('Content-Disposition');217218 // woot! callback available219 if (fn) return fn(err);220221 // lost in limbo if there's no callback222 if (self.headerSent) return;223224 return req.next(err);225 }226227 fn && fn();228 };229230 // transfer231 options.path = encodeURIComponent(path);232 send(this.req, this, next, options);233};234235/**236 * Transfer the file at the given `path` as an attachment.237 *238 * Optionally providing an alternate attachment `filename`,239 * and optional callback `fn(err)`. The callback is invoked240 * when the data transfer is complete, or when an error has241 * ocurred. Be sure to check `res.sendHeader` if you plan to respond.242 *243 * @param {String} path244 * @param {String|Function} filename or fn245 * @param {Function} fn246 * @api public247 */248249res.download = function(path, filename, fn){250 // support function as second arg251 if ('function' == typeof filename) {252 fn = filename;253 filename = null;254 }255256 return this.attachment(filename || path).sendfile(path, fn);257};258259/**260 * Set _Content-Type_ response header passed through `mime.lookup()`.261 *262 * Examples:263 *264 * var filename = 'path/to/image.png';265 * res.contentType(filename);266 * // res.headers['Content-Type'] is now "image/png"267 *268 * res.contentType('.html');269 * res.contentType('html');270 * res.contentType('json');271 * res.contentType('png');272 * res.type('png');273 *274 * @param {String} type275 * @return {ServerResponse} for chaining276 * @api public277 */278279res.contentType =280res.type = function(type){281 return this.header('Content-Type', mime.lookup(type));282};283284/**285 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.286 *287 * @param {String} filename288 * @return {ServerResponse}289 * @api public290 */291292res.attachment = function(filename){293 if (filename) this.type(filename);294 this.header('Content-Disposition', filename295 ? 'attachment; filename="' + basename(filename) + '"'296 : 'attachment');297 return this;298};299300/**301 * Set header `field` to `val`, or pass302 * an object of of header fields.303 *304 * Examples:305 *306 * res.set('Accept', 'application/json');307 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });308 *309 * @param {String|Object} field310 * @param {String} val311 * @return {ServerResponse} for chaining312 * @api public313 */314315res.set = function(field, val){316 if (2 == arguments.length) {317 this.setHeader(field, val);318 } else {319 for (var key in field) {320 this.setHeader(key, field[key]);321 }322 }323 return this;324};325326/**327 * Get value for header `field`.328 *329 * @param {String} field330 * @return {String}331 * @api public332 */333334res.get = function(field){335 return this.getHeader(field);336};337338/**339 * Set or get response header `field` with optional `val`.340 *341 * @param {String} name342 * @param {String} val343 * @return {ServerResponse} for chaining344 * @api public345 */346347res.header = function(field, val){348 if (1 == arguments.length) return this.getHeader(field);349 this.setHeader(field, val);350 return this;351};352353/**354 * Clear cookie `name`.355 *356 * @param {String} name357 * @param {Object} options358 * @param {ServerResponse} for chaining359 * @api public360 */361362res.clearCookie = function(name, options){363 var opts = { expires: new Date(1), path: this.app.get('root') };364 return this.cookie(name, '', options365 ? utils.merge(opts, options)366 : opts);367};368369/**370 * Set a signed cookie with the given `name` and `val`.371 * See `res.cookie()` for details.372 *373 * @param {String} name374 * @param {String|Object} val375 * @param {Object} options376 * @api public377 */378379res.signedCookie = function(name, val, options){380 var secret = this.req.secret;381 if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');382 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);383 val = utils.sign(val, secret);384 return this.cookie(name, val, options);385};386387/**388 * Set cookie `name` to `val`, with the given `options`.389 *390 * Options:391 *392 * - `maxAge` max-age in milliseconds, converted to `expires`393 * - `path` defaults to the "root" setting which is typically "/"394 *395 * Examples:396 *397 * // "Remember Me" for 15 minutes398 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });399 *400 * // save as above401 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })402 *403 * @param {String} name404 * @param {String|Object} val405 * @param {Options} options406 * @api public407 */408409res.cookie = function(name, val, options){410 options = options || {};411 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);412 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);413 if (undefined === options.path) options.path = this.app.set('root');414 var cookie = utils.serializeCookie(name, val, options);415 this.header('Set-Cookie', cookie);416 return this;417};418419/**420 * Redirect to the given `url` with optional response `status`421 * defaulting to 302.422 *423 * The given `url` can also be the name of a mapped url, for424 * example by default express supports "back" which redirects425 * to the _Referrer_ or _Referer_ headers or the application's426 * "root" setting. Express also supports "root" out of the box,427 * which can be set via `app.set('root', '/blog');`.428 *429 * Examples:430 *431 * res.redirect('/foo/bar');432 * res.redirect('http://example.com');433 * res.redirect(301, 'http://example.com');434 *435 * Redirect Mapping:436 * 437 * To extend the redirect mapping capabilities that Express provides,438 * we may use the `app.redirect()` method:439 * 440 * app.redirect('google', 'http://google.com');441 * 442 * Now in a route we may call:443 *444 * res.redirect('google');445 *446 * We may also map dynamic redirects:447 *448 * app.redirect('comments', function(req, res){449 * return '/post/' + req.params.id + '/comments';450 * });451 *452 * So now we may do the following, and the redirect will dynamically adjust to453 * the context of the request. If we called this route with _GET /post/12_ our454 * redirect _Location_ would be _/post/12/comments_.455 *456 * app.get('/post/:id', function(req, res){457 * res.redirect('comments');458 * });459 *460 * Unless an absolute `url` is given, the app's mount-point461 * will be respected. For example if we redirect to `/posts`,462 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.463 *464 * @param {String} url465 * @param {Number} code466 * @api public467 */468469res.redirect = function(url){470 var app = this.app471 , req = this.req472 , root = app.get('root')473 , head = 'HEAD' == req.method474 , status = 302475 , body;476477 // allow status / url478 if (2 == arguments.length) {479 status = url;480 url = arguments[1];481 }482483 // Setup redirect map484 var map = {485 back: req.header('Referrer', root)486 , home: root487 };488489 // Support custom redirect map490 map.__proto__ = app.redirects;491492 // Attempt mapped redirect493 var mapped = 'function' == typeof map[url]494 ? map[url](req, this)495 : map[url];496497 // Perform redirect498 url = mapped || url;499500 // Relative501 if (!~url.indexOf('://')) {502 // Respect mount-point503 if (0 != url.indexOf(app.route)) url = app.route + url;504505 // Absolute506 var host = req.header('Host')507 , tls = false // TODO: req.secure;508509 url = 'http' + (tls ? 's' : '') + '://' + host + url;510 }511512 // Support text/{plain,html} by default513 if (req.accepts('html')) {514 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';515 this.header('Content-Type', 'text/html');516 } else {517 body = statusCodes[status] + '. Redirecting to ' + url;518 this.header('Content-Type', 'text/plain');519 }520521 // Respond522 this.statusCode = status;523 this.header('Location', url);524 this.end(head ? null : body);525};526527/**528 * Render `view` with the given `options` and optional callback `fn`.529 * When a callback function is given a response will _not_ be made530 * automatically, otherwise a response of _200_ and _text/html_ is given.531 *532 * Options:533 * 534 * - `status` Response status code (`res.statusCode`)535 * - `charset` Set the charset (`res.charset`)536 *537 * Reserved locals:538 *539 * - `cache` boolean hinting to the engine it should cache540 * - `filename` filename of the view being rendered541 *542 * @param {String} view543 * @param {Object|Function} options or callback function544 * @param {Function} fn545 * @api public546 */547548res.render = function(view, options, fn){549 var self = this550 , options = options || {}551 , req = this.req552 , app = req.app;553554 // support callback function as second arg555 if ('function' == typeof options) {556 fn = options, options = {};557 }558559 function render() {560 // merge res.locals561 options.locals = self.locals;562563 // default callback to respond564 fn = fn || function(err, str){565 if (err) return req.next(err);566 self.send(str);567 };568569 // render570 app.render(view, options, fn);571 }572573 // invoke view callbacks574 var callbacks = app.viewCallbacks575 , pending = callbacks.length576 , len = pending577 , done;578579 if (len) {580 for (var i = 0; i < len; ++i) {581 callbacks[i](req, self, function(err){582 if (done) return;583584 if (err) {585 req.next(err);586 done = true;587 return;588 }589590 --pending || render();591 });592 }593 } else {594 render();595 }596};