response.js
This file
Path
lib/response.js
646 lines · 14.9 KiB · JavaScript
Last changed by
Added: allow [] in jsonp callback. Closes #1128TJ Holowaychukbefore adoptiondf2584c
History of this fileTake it
12/**3 * Module dependencies.4 */56var fs = require('fs')7 , http = require('http')8 , path = require('path')9 , connect = require('connect')10 , utils = connect.utils11 , normalizeType = require('./utils').normalizeType12 , normalizeTypes = require('./utils').normalizeTypes13 , statusCodes = http.STATUS_CODES14 , send = connect.static.send15 , crc = require('crc')16 , mime = require('mime')17 , 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 * Send a response.44 *45 * Examples:46 *47 * res.send(new Buffer('wahoo'));48 * res.send({ some: 'json' });49 * res.send('<p>some html</p>');50 * res.send(404, 'Sorry, cant find that');51 * res.send(404);52 *53 * @param {Mixed} body or status54 * @param {Mixed} body55 * @return {ServerResponse}56 * @api public57 */5859res.send = function(body){60 var req = this.req61 , head = 'HEAD' == req.method62 , len;6364 // allow status / body65 if (2 == arguments.length) {66 this.statusCode = body;67 body = arguments[1];68 }69 70 // convert string objects to primitives71 if (body instanceof String) body = body.toString();7273 switch (typeof body) {74 // response status75 case 'number':76 this.get('Content-Type') || this.type('txt');77 this.statusCode = body;78 body = http.STATUS_CODES[body];79 break;80 // string defaulting to html81 case 'string':82 if (!this.get('Content-Type')) {83 this.charset = this.charset || 'utf-8';84 this.type('html');85 }86 break;87 case 'boolean':88 case 'object':89 if (null == body) {90 body = '';91 } else if (Buffer.isBuffer(body)) {92 this.get('Content-Type') || this.type('bin');93 } else {94 return this.json(body);95 }96 break;97 }9899 // populate Content-Length100 if (undefined !== body && !this.get('Content-Length')) {101 this.set('Content-Length', len = Buffer.isBuffer(body)102 ? body.length103 : Buffer.byteLength(body));104 }105106 // ETag support107 // TODO: W/ support108 if (len > 1024) {109 if (!this.get('ETag')) this.set('ETag', Buffer.isBuffer(body)110 ? crc.buffer.crc32(body)111 : crc.crc32(body));112 if (req.fresh) this.statusCode = 304;113 }114115 // strip irrelevant headers116 if (204 == this.statusCode || 304 == this.statusCode) {117 this.removeHeader('Content-Type');118 this.removeHeader('Content-Length');119 body = '';120 }121122 // respond123 this.end(head ? null : body);124 return this;125};126127/**128 * Send JSON response.129 *130 * Examples:131 *132 * res.json(null);133 * res.json({ user: 'tj' });134 * res.json(500, 'oh noes!');135 * res.json(404, 'I dont have that');136 *137 * @param {Mixed} obj or status138 * @param {Mixed} obj139 * @return {ServerResponse}140 * @api public141 */142143res.json = function(obj){144 // allow status / body145 if (2 == arguments.length) {146 this.statusCode = obj;147 obj = arguments[1];148 }149150 var app = this.app151 , jsonp = app.get('jsonp callback')152 , replacer = app.get('json replacer')153 , spaces = app.get('json spaces')154 , body = JSON.stringify(obj, replacer, spaces)155 , callback = this.req.query.callback;156157 this.charset = this.charset || 'utf-8';158 this.set('Content-Type', 'application/json');159160 if (callback && jsonp) {161 this.set('Content-Type', 'text/javascript');162 body = callback.replace(/[^[]\w$.]/g, '') + '(' + body + ');';163 }164165 return this.send(body);166};167168/**169 * Transfer the file at the given `path`.170 * 171 * Automatically sets the _Content-Type_ response header field.172 * The callback `fn(err)` is invoked when the transfer is complete173 * or when an error occurs. Be sure to check `res.sentHeader`174 * if you wish to attempt responding, as the header and some data175 * may have already been transferred.176 *177 * Options:178 *179 * - `maxAge` defaulting to 0180 * - `root` root directory for relative filenames181 *182 * Examples:183 *184 * The following example illustrates how `res.sendfile()` may185 * be used as an alternative for the `static()` middleware for186 * dynamic situations. The code backing `res.sendfile()` is actually187 * the same code, so HTTP cache support etc is identical.188 *189 * app.get('/user/:uid/photos/:file', function(req, res){190 * var uid = req.params.uid191 * , file = req.params.file;192 * 193 * req.user.mayViewFilesFrom(uid, function(yes){194 * if (yes) {195 * res.sendfile('/uploads/' + uid + '/' + file);196 * } else {197 * res.send(403, 'Sorry! you cant see that.');198 * }199 * });200 * });201 *202 * @param {String} path203 * @param {Object|Function} options or fn204 * @param {Function} fn205 * @api public206 */207208res.sendfile = function(path, options, fn){209 var self = this210 , req = self.req211 , next = this.req.next212 , options = options || {};213214 // support function as second arg215 if ('function' == typeof options) {216 fn = options;217 options = {};218 }219220 // callback221 options.callback = function(err){222 if (err) {223 // cast ENOENT224 if ('ENOENT' == err.code) err = utils.error(404);225226 // ditch content-disposition to prevent funky responses227 if (!self.headerSent) self.removeHeader('Content-Disposition');228229 // woot! callback available230 if (fn) return fn(err);231232 // lost in limbo if there's no callback233 if (self.headerSent) return;234235 return req.next(err);236 }237238 fn && fn();239 };240241 // transfer242 options.path = encodeURIComponent(path);243 send(this.req, this, next, options);244};245246/**247 * Transfer the file at the given `path` as an attachment.248 *249 * Optionally providing an alternate attachment `filename`,250 * and optional callback `fn(err)`. The callback is invoked251 * when the data transfer is complete, or when an error has252 * ocurred. Be sure to check `res.headerSent` if you plan to respond.253 *254 * This method uses `res.attachment()` and `res.sendfile()`.255 *256 * @param {String} path257 * @param {String|Function} filename or fn258 * @param {Function} fn259 * @api public260 */261262res.download = function(path, filename, fn){263 // support function as second arg264 if ('function' == typeof filename) {265 fn = filename;266 filename = null;267 }268269 return this.attachment(filename || path).sendfile(path, fn);270};271272/**273 * Set _Content-Type_ response header with `type` through `mime.lookup()`274 * when it does not contain "/", or set the Content-Type to `type` otherwise.275 *276 * Examples:277 *278 * res.type('.html');279 * res.type('html');280 * res.type('json');281 * res.type('application/json');282 * res.type('png');283 *284 * @param {String} type285 * @return {ServerResponse} for chaining286 * @api public287 */288289res.contentType =290res.type = function(type){291 return this.set('Content-Type', ~type.indexOf('/')292 ? type293 : mime.lookup(type));294};295296/**297 * Respond to the Acceptable formats using an `obj`298 * of mime-type callbacks.299 *300 * This method uses `req.accepted`, an array of301 * acceptable types ordered by their quality values.302 * When "Accept" is not present the _first_ callback303 * is invoked, otherwise the first match is used. When304 * no match is performed the server responds with305 * 406 "Not Acceptable".306 *307 * Content-Type is set for you, however if you choose308 * you may alter this within the callback using `res.type()`309 * or `res.set('Content-Type', ...)`.310 *311 * res.format({312 * 'text/plain': function(){313 * res.send('hey');314 * },315 * 316 * 'text/html': function(){317 * res.send('<p>hey</p>');318 * },319 * 320 * 'appliation/json': function(){321 * res.send({ message: 'hey' });322 * }323 * });324 *325 * In addition to canonicalized MIME types you may326 * also use extnames mapped to these types:327 *328 * res.format({329 * text: function(){330 * res.send('hey');331 * },332 * 333 * html: function(){334 * res.send('<p>hey</p>');335 * },336 * 337 * json: function(){338 * res.send({ message: 'hey' });339 * }340 * });341 *342 * @param {Object} obj343 * @return {ServerResponse} for chaining344 * @api public345 */346347res.format = function(obj){348 var keys = Object.keys(obj)349 , req = this.req350 , next = req.next351 , key = req.accepts(keys);352353 this.set('Vary', 'Accept');354355 if (key) {356 this.set('Content-Type', normalizeType(key));357 obj[key](req, this, next);358 } else {359 var err = new Error('Not Acceptable');360 err.status = 406;361 err.types = normalizeTypes(keys);362 next(err);363 }364365 return this;366};367368/**369 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.370 *371 * @param {String} filename372 * @return {ServerResponse}373 * @api public374 */375376res.attachment = function(filename){377 if (filename) this.type(extname(filename));378 this.set('Content-Disposition', filename379 ? 'attachment; filename="' + basename(filename) + '"'380 : 'attachment');381 return this;382};383384/**385 * Set header `field` to `val`, or pass386 * an object of of header fields.387 *388 * Examples:389 *390 * res.set('Accept', 'application/json');391 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });392 *393 * Aliased as `res.header()`. 394 *395 * @param {String|Object} field396 * @param {String} val397 * @return {ServerResponse} for chaining398 * @api public399 */400401res.set = 402res.header = function(field, val){403 if (2 == arguments.length) {404 this.setHeader(field, '' + val);405 } else {406 for (var key in field) {407 this.setHeader(key, '' + field[key]);408 }409 }410 return this;411};412413/**414 * Get value for header `field`.415 *416 * @param {String} field417 * @return {String}418 * @api public419 */420421res.get = function(field){422 return this.getHeader(field);423};424425/**426 * Clear cookie `name`.427 *428 * @param {String} name429 * @param {Object} options430 * @param {ServerResponse} for chaining431 * @api public432 */433434res.clearCookie = function(name, options){435 var opts = { expires: new Date(1), path: '/' };436 return this.cookie(name, '', options437 ? utils.merge(opts, options)438 : opts);439};440441/**442 * Set a signed cookie with the given `name` and `val`.443 * See `res.cookie()` for details.444 *445 * @param {String} name446 * @param {String|Object} val447 * @param {Object} options448 * @api public449 */450451res.signedCookie = function(name, val, options){452 var secret = this.req.secret;453 if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');454 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);455 val = utils.sign(val, secret);456 return this.cookie(name, val, options);457};458459/**460 * Set cookie `name` to `val`, with the given `options`.461 *462 * Options:463 *464 * - `maxAge` max-age in milliseconds, converted to `expires`465 * - `path` defaults to "/"466 *467 * Examples:468 *469 * // "Remember Me" for 15 minutes470 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });471 *472 * // save as above473 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })474 *475 * @param {String} name476 * @param {String|Object} val477 * @param {Options} options478 * @api public479 */480481res.cookie = function(name, val, options){482 options = options || {};483 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);484 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);485 if (null == options.path) options.path = '/';486 var cookie = utils.serializeCookie(name, val, options);487 this.set('Set-Cookie', cookie);488 return this;489};490491/**492 * Redirect to the given `url` with optional response `status`493 * defaulting to 302.494 *495 * The given `url` can also be the name of a mapped url, for496 * example by default express supports "back" which redirects497 * to the _Referrer_ or _Referer_ headers or "/".498 *499 * Examples:500 *501 * res.redirect('/foo/bar');502 * res.redirect('http://example.com');503 * res.redirect(301, 'http://example.com');504 * res.redirect('../login'); // /blog/post/1 -> /blog/login505 *506 * Mounting:507 *508 * When an application is mounted, and `res.redirect()`509 * is given a path that does _not_ lead with "/". For 510 * example suppose a "blog" app is mounted at "/blog",511 * the following redirect would result in "/blog/login":512 *513 * res.redirect('login');514 *515 * While the leading slash would result in a redirect to "/login":516 *517 * res.redirect('/login');518 *519 * @param {String} url520 * @param {Number} code521 * @api public522 */523524res.redirect = function(url){525 var app = this.app526 , req = this.req527 , head = 'HEAD' == req.method528 , status = 302529 , body;530531 // allow status / url532 if (2 == arguments.length) {533 status = url;534 url = arguments[1];535 }536537 // setup redirect map538 var map = { back: req.get('Referrer') || '/' };539540 // perform redirect541 url = map[url] || url;542543 // relative544 if (!~url.indexOf('://')) {545 var path = app.path();546547 // relative to path548 if (0 == url.indexOf('./') || 0 == url.indexOf('..')) {549 url = req.path + '/' + url;550 // relative to mount-point551 } else if ('/' != url[0]) {552 url = path + '/' + url;553 }554555 // Absolute556 var host = req.get('Host');557 url = req.protocol + '://' + host + url;558 }559560 // Support text/{plain,html} by default561 this.format({562 text: function(){563 body = statusCodes[status] + '. Redirecting to ' + url;564 },565566 html: function(){567 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';568 }569 })570571 // Respond572 this.statusCode = status;573 this.set('Location', url);574 this.end(head ? null : body);575};576577/**578 * Render `view` with the given `options` and optional callback `fn`.579 * When a callback function is given a response will _not_ be made580 * automatically, otherwise a response of _200_ and _text/html_ is given.581 *582 * Options:583 * 584 * - `status` Response status code (`res.statusCode`)585 * - `charset` Set the charset (`res.charset`)586 *587 * Reserved locals:588 *589 * - `cache` boolean hinting to the engine it should cache590 * - `filename` filename of the view being rendered591 *592 * @param {String} view593 * @param {Object|Function} options or callback function594 * @param {Function} fn595 * @api public596 */597598res.render = function(view, options, fn){599 var self = this600 , options = options || {}601 , req = this.req602 , app = req.app;603604 // support callback function as second arg605 if ('function' == typeof options) {606 fn = options, options = {};607 }608609 function render() {610 // merge res.locals611 options.locals = self.locals;612613 // default callback to respond614 fn = fn || function(err, str){615 if (err) return req.next(err);616 self.send(str);617 };618619 // render620 app.render(view, options, fn);621 }622623 // invoke view callbacks624 var callbacks = app.viewCallbacks.concat(self.viewCallbacks)625 , pending = callbacks.length626 , len = pending627 , done;628629 if (len) {630 for (var i = 0; i < len; ++i) {631 callbacks[i](req, self, function(err){632 if (done) return;633634 if (err) {635 req.next(err);636 done = true;637 return;638 }639640 --pending || render();641 });642 }643 } else {644 render();645 }646};