response.js
This file
Path
lib/response.js
450 lines · 10.6 KiB · JavaScript
Last changed by
fixed `res.sendfile()` 404 supportTj Holowaychukbefore adoptiond2df055
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 , parseRange = require('./utils').parseRange19 , res = http.ServerResponse.prototype20 , send = connect.static.send21 , mime = require('mime')22 , basename = path.basename23 , join = path.join;2425/**26 * Send a response.27 *28 * Examples:29 *30 * res.send(new Buffer('wahoo'));31 * res.send({ some: 'json' });32 * res.send('<p>some html</p>');33 * res.send(404, 'Sorry, cant find that');34 * res.send(404);35 *36 * @param {Mixed} body or status37 * @param {Mixed} body38 * @return {ServerResponse}39 * @api public40 */4142res.send = function(body){43 // allow status / body44 if (2 == arguments.length) {45 this.statusCode = body;46 body = arguments[1];47 }4849 switch (typeof body) {50 // response status51 case 'number':52 this.header('Content-Type') || this.contentType('.txt');53 this.statusCode = body;54 body = http.STATUS_CODES[body];55 break;56 // string defaulting to html57 case 'string':58 if (!this.header('Content-Type')) {59 this.charset = this.charset || 'utf-8';60 this.contentType('.html');61 }62 break;63 case 'boolean':64 case 'object':65 if (null == body) {66 body = '';67 } else if (Buffer.isBuffer(body)) {68 this.header('Content-Type') || this.contentType('.bin');69 } else {70 return this.json(body);71 }72 break;73 }7475 // populate Content-Length76 if (undefined !== body && !this.header('Content-Length')) {77 this.header('Content-Length', Buffer.isBuffer(body)78 ? body.length79 : Buffer.byteLength(body));80 }8182 // strip irrelevant headers83 if (204 == this.statusCode || 304 == this.statusCode) {84 this.removeHeader('Content-Type');85 this.removeHeader('Content-Length');86 body = '';87 }8889 // respond90 this.end('HEAD' == this.req.method ? undefined : body);91 return this;92};9394/**95 * Send JSON response.96 *97 * Examples:98 *99 * res.json(null);100 * res.json({ user: 'tj' });101 * res.json(500, 'oh noes!');102 * res.json(404, 'I dont have that');103 *104 * @param {Mixed} obj or status105 * @param {Mixed} obj106 * @return {ServerResponse}107 * @api public108 */109110res.json = function(obj){111 // allow status / body112 if (2 == arguments.length) {113 this.statusCode = obj;114 obj = arguments[1];115 }116117 var body = JSON.stringify(obj)118 , callback = this.req.query.callback119 , jsonp = this.app.enabled('jsonp callback');120121 this.charset = this.charset || 'utf-8';122 this.header('Content-Type', 'application/json');123124 if (callback && jsonp) {125 this.header('Content-Type', 'text/javascript');126 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';127 }128129 return this.send(body);130};131132/**133 * Set status `code`.134 *135 * @param {Number} code136 * @return {ServerResponse}137 * @api public138 */139140res.status = function(code){141 this.statusCode = code;142 return this;143};144145/**146 * Transfer the file at the given `path`.147 * 148 * Automatically sets the _Content-Type_ response header field.149 * The callback `fn(err)` is invoked when the transfer is complete150 * or when an error occurs. Be sure to check `res.sentHeader`151 * if you wish to attempt responding, as the header and some data152 * may have already been transferred.153 *154 * Options:155 *156 * - `maxAge` defaulting to 0157 * - `root` root directory for relative filenames158 *159 * @param {String} path160 * @param {Object|Function} options or fn161 * @param {Function} fn162 * @api public163 */164165res.sendfile = function(path, options, fn){166 var self = this167 , req = self.req168 , next = this.req.next169 , options = options || {};170171 // support function as second arg172 if ('function' == typeof options) {173 fn = options;174 options = {};175 }176177 // callback178 options.callback = function(err){179 // TODO: remove when node adds this180 self.sentHeader = !! self._header;181182 // error183 if (err) {184 // ditch content-disposition to prevent funky responses185 if (!self.sentHeader) self.removeHeader('Content-Disposition');186187 // not found188 if ('ENOENT' == err.code) return req.next();189190 // lost in limbo if there's no callback191 if (self.sentHeader) return fn && fn(err);192193 // callback available194 if (fn) return fn(err);195196 return req.next(err);197 }198199 fn && fn();200 };201202 // transfer203 options.path = encodeURIComponent(path);204 send(this.req, this, next, options);205};206207/**208 * Transfer the file at the given `path` as an attachment.209 *210 * Optionally providing an alternate attachment `filename`,211 * and optional callback `fn(err)`. The callback is invoked212 * when the data transfer is complete, or when an error has213 * ocurred. Be sure to check `res.sendHeader` if you plan to respond.214 *215 * @param {String} path216 * @param {String|Function} filename or fn217 * @param {Function} fn218 * @api public219 */220221res.download = function(path, filename, fn){222 // support function as second arg223 if ('function' == typeof filename) {224 fn = filename;225 filename = null;226 }227228 return this.attachment(filename || path).sendfile(path, fn);229};230231/**232 * Set _Content-Type_ response header passed through `mime.lookup()`.233 *234 * Examples:235 *236 * var filename = 'path/to/image.png';237 * res.contentType(filename);238 * // res.headers['Content-Type'] is now "image/png"239 *240 * res.contentType('.html');241 * res.contentType('html');242 * res.contentType('json');243 * res.contentType('png');244 *245 * @param {String} type246 * @return {ServerResponse} for chaining247 * @api public248 */249250res.contentType = function(type){251 return this.header('Content-Type', mime.lookup(type));252};253254/**255 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.256 *257 * @param {String} filename258 * @return {ServerResponse}259 * @api public260 */261262res.attachment = function(filename){263 if (filename) this.contentType(filename);264 this.header('Content-Disposition', filename265 ? 'attachment; filename="' + basename(filename) + '"'266 : 'attachment');267 return this;268};269270/**271 * Set header `field` to `val`.272 *273 * @param {String} field274 * @param {String} val275 * @return {ServerResponse} for chaining276 * @api public277 */278279res.set = function(field, val){280 this.setHeader(field, val);281 return this;282};283284/**285 * Get value for header `field`.286 *287 * @param {String} field288 * @return {String}289 * @api public290 */291292res.get = function(field){293 return this.getHeader(field);294};295296/**297 * Set or get response header `field` with optional `val`.298 *299 * @param {String} name300 * @param {String} val301 * @return {ServerResponse} for chaining302 * @api public303 */304305res.header = function(field, val){306 if (1 == arguments.length) return this.getHeader(field);307 this.setHeader(field, val);308 return this;309};310311/**312 * Clear cookie `name`.313 *314 * @param {String} name315 * @param {Object} options316 * @param {ServerResponse} for chaining317 * @api public318 */319320res.clearCookie = function(name, options){321 var opts = { expires: new Date(1) };322 return this.cookie(name, '', options323 ? utils.merge(options, opts)324 : opts);325};326327/**328 * Set cookie `name` to `val`, with the given `options`.329 *330 * Options:331 *332 * - `maxAge` max-age in milliseconds, converted to `expires`333 * - `path` defaults to the "basepath" setting which is typically "/"334 *335 * Examples:336 *337 * // "Remember Me" for 15 minutes338 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });339 *340 * // save as above341 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })342 *343 * @param {String} name344 * @param {String} val345 * @param {Options} options346 * @api public347 */348349res.cookie = function(name, val, options){350 options = options || {};351 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);352 if (undefined === options.path) options.path = this.app.set('basepath');353 var cookie = utils.serializeCookie(name, val, options);354 this.header('Set-Cookie', cookie);355 return this;356};357358/**359 * Redirect to the given `url` with optional response `status`360 * defauling to 302.361 *362 * The given `url` can also be the name of a mapped url, for363 * example by default express supports "back" which redirects364 * to the _Referrer_ or _Referer_ headers or the application's365 * "basepath" setting. Express also supports "basepath" out of the box,366 * which can be set via `app.set('basepath', '/blog');`.367 *368 * Redirect Mapping:369 * 370 * To extend the redirect mapping capabilities that Express provides,371 * we may use the `app.redirect()` method:372 * 373 * app.redirect('google', 'http://google.com');374 * 375 * Now in a route we may call:376 *377 * res.redirect('google');378 *379 * We may also map dynamic redirects:380 *381 * app.redirect('comments', function(req, res){382 * return '/post/' + req.params.id + '/comments';383 * });384 *385 * So now we may do the following, and the redirect will dynamically adjust to386 * the context of the request. If we called this route with _GET /post/12_ our387 * redirect _Location_ would be _/post/12/comments_.388 *389 * app.get('/post/:id', function(req, res){390 * res.redirect('comments');391 * });392 *393 * Unless an absolute `url` is given, the app's mount-point394 * will be respected. For example if we redirect to `/posts`,395 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.396 *397 * @param {String} url398 * @param {Number} code399 * @api public400 */401402res.redirect = function(url, status){403 var app = this.app404 , req = this.req405 , base = app.set('basepath') || app.route406 , status = status || 302407 , body;408409 // Setup redirect map410 var map = {411 back: req.header('Referrer', base)412 , home: base413 };414415 // Support custom redirect map416 map.__proto__ = app.redirects;417418 // Attempt mapped redirect419 var mapped = 'function' == typeof map[url]420 ? map[url](req, this)421 : map[url];422423 // Perform redirect424 url = mapped || url;425426 // Relative427 if (!~url.indexOf('://')) {428 // Respect mount-point429 if ('/' != base && 0 != url.indexOf(base)) url = base + url;430431 // Absolute432 var host = req.headers.host433 , tls = req.connection.encrypted;434 url = 'http' + (tls ? 's' : '') + '://' + host + url;435 }436437 // Support text/{plain,html} by default438 if (req.accepts('html')) {439 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';440 this.header('Content-Type', 'text/html');441 } else {442 body = statusCodes[status] + '. Redirecting to ' + url;443 this.header('Content-Type', 'text/plain');444 }445446 // Respond447 this.statusCode = status;448 this.header('Location', url);449 this.end(body);450};