response.js
This file
Path
lib/response.js
437 lines · 10.1 KiB · JavaScript
Last changed by
Added `res.get(field)` as an alternative to `res.header(field)`Tj Holowaychukbefore adoptionc8c6aa2
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`. Automatically sets 147 * the _Content-Type_ response header field. `next()` is called148 * when `path` is a directory, or when an error occurs.149 *150 * Options:151 *152 * - `maxAge` defaulting to 0153 * - `root` root directory for relative filenames154 *155 * @param {String} path156 * @param {Object|Function} options or fn157 * @param {Function} fn158 * @api public159 */160161res.sendfile = function(path, options, fn){162 var next = this.req.next;163 options = options || {};164165 // support function as second arg166 if ('function' == typeof options) {167 fn = options;168 options = {};169 }170171 options.path = encodeURIComponent(path);172 options.callback = fn;173 send(this.req, this, next, options);174};175176/**177 * Set _Content-Type_ response header passed through `mime.lookup()`.178 *179 * Examples:180 *181 * var filename = 'path/to/image.png';182 * res.contentType(filename);183 * // res.headers['Content-Type'] is now "image/png"184 *185 * res.contentType('.html');186 * res.contentType('html');187 * res.contentType('json');188 * res.contentType('png');189 *190 * @param {String} type191 * @return {ServerResponse} for chaining192 * @api public193 */194195res.contentType = function(type){196 return this.header('Content-Type', mime.lookup(type));197};198199/**200 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.201 *202 * @param {String} filename203 * @return {ServerResponse}204 * @api public205 */206207res.attachment = function(filename){208 if (filename) this.contentType(filename);209 this.header('Content-Disposition', filename210 ? 'attachment; filename="' + basename(filename) + '"'211 : 'attachment');212 return this;213};214215/**216 * Transfer the file at the given `path`, with optional 217 * `filename` as an attachment and optional callback `fn(err)`,218 * and optional `fn2(err)` which is invoked when an error has219 * occurred after header has been sent.220 *221 * @param {String} path222 * @param {String|Function} filename or fn223 * @param {Function} fn224 * @param {Function} fn2225 * @api public226 */227228res.download = function(path, filename, fn, fn2){229 var self = this;230231 // support callback as second arg232 if ('function' == typeof filename) {233 fn2 = fn;234 fn = filename;235 filename = null;236 }237238 // transfer the file239 this.attachment(filename || path).sendfile(path, function(err){240 var sentHeader = self._header;241 if (err) {242 if (!sentHeader) self.removeHeader('Content-Disposition');243 if (sentHeader) {244 fn2 && fn2(err);245 } else if (fn) {246 fn(err);247 } else {248 self.req.next(err);249 }250 } else if (fn) {251 fn();252 }253 });254};255256/**257 * Set header `field` to `val`.258 *259 * @param {String} field260 * @param {String} val261 * @return {ServerResponse} for chaining262 * @api public263 */264265res.set = function(field, val){266 this.setHeader(field, val);267 return this;268};269270/**271 * Get value for header `field`.272 *273 * @param {String} field274 * @return {String}275 * @api public276 */277278res.get = function(field){279 return this.getHeader(field);280};281282/**283 * Set or get response header `field` with optional `val`.284 *285 * @param {String} name286 * @param {String} val287 * @return {ServerResponse} for chaining288 * @api public289 */290291res.header = function(field, val){292 if (1 == arguments.length) return this.getHeader(field);293 this.setHeader(field, val);294 return this;295};296297/**298 * Clear cookie `name`.299 *300 * @param {String} name301 * @param {Object} options302 * @param {ServerResponse} for chaining303 * @api public304 */305306res.clearCookie = function(name, options){307 var opts = { expires: new Date(1) };308 return this.cookie(name, '', options309 ? utils.merge(options, opts)310 : opts);311};312313/**314 * Set cookie `name` to `val`, with the given `options`.315 *316 * Options:317 *318 * - `maxAge` max-age in milliseconds, converted to `expires`319 * - `path` defaults to the "home" setting which is typically "/"320 *321 * Examples:322 *323 * // "Remember Me" for 15 minutes324 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });325 *326 * // save as above327 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })328 *329 * @param {String} name330 * @param {String} val331 * @param {Options} options332 * @api public333 */334335res.cookie = function(name, val, options){336 options = options || {};337 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);338 if (undefined === options.path) options.path = this.app.set('home');339 var cookie = utils.serializeCookie(name, val, options);340 this.header('Set-Cookie', cookie);341 return this;342};343344/**345 * Redirect to the given `url` with optional response `status`346 * defauling to 302.347 *348 * The given `url` can also be the name of a mapped url, for349 * example by default express supports "back" which redirects350 * to the _Referrer_ or _Referer_ headers or the application's351 * "home" setting. Express also supports "home" out of the box,352 * which can be set via `app.set('home', '/blog');`, and defaults353 * to '/'.354 *355 * Redirect Mapping:356 * 357 * To extend the redirect mapping capabilities that Express provides,358 * we may use the `app.redirect()` method:359 * 360 * app.redirect('google', 'http://google.com');361 * 362 * Now in a route we may call:363 *364 * res.redirect('google');365 *366 * We may also map dynamic redirects:367 *368 * app.redirect('comments', function(req, res){369 * return '/post/' + req.params.id + '/comments';370 * });371 *372 * So now we may do the following, and the redirect will dynamically adjust to373 * the context of the request. If we called this route with _GET /post/12_ our374 * redirect _Location_ would be _/post/12/comments_.375 *376 * app.get('/post/:id', function(req, res){377 * res.redirect('comments');378 * });379 *380 * Unless an absolute `url` is given, the app's mount-point381 * will be respected. For example if we redirect to `/posts`,382 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.383 *384 * @param {String} url385 * @param {Number} code386 * @api public387 */388389res.redirect = function(url, status){390 var app = this.app391 , req = this.req392 , base = app.set('home') || '/'393 , status = status || 302394 , body;395396 // Setup redirect map397 var map = {398 back: req.header('Referrer', base)399 , home: base400 };401402 // Support custom redirect map403 map.__proto__ = app.redirects;404405 // Attempt mapped redirect406 var mapped = 'function' == typeof map[url]407 ? map[url](req, this)408 : map[url];409410 // Perform redirect411 url = mapped || url;412413 // Relative414 if (!~url.indexOf('://')) {415 // Respect mount-point416 if (app.route) url = join(app.route, url);417418 // Absolute419 var host = req.headers.host420 , tls = req.connection.encrypted;421 url = 'http' + (tls ? 's' : '') + '://' + host + url;422 }423424 // Support text/{plain,html} by default425 if (req.accepts('html')) {426 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';427 this.header('Content-Type', 'text/html');428 } else {429 body = statusCodes[status] + '. Redirecting to ' + url;430 this.header('Content-Type', 'text/plain');431 }432433 // Respond434 this.statusCode = status;435 this.header('Location', url);436 this.end(body);437};