response.js
This file
Path
lib/response.js
453 lines · 10.6 KiB · JavaScript
Last changed by
refactored `res.send()`Tj Holowaychukbefore adoption2c734e2
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 var req = this.req44 , head = 'HEAD' == req.method;4546 // allow status / body47 if (2 == arguments.length) {48 this.statusCode = body;49 body = arguments[1];50 }5152 switch (typeof body) {53 // response status54 case 'number':55 this.header('Content-Type') || this.contentType('.txt');56 this.statusCode = body;57 body = http.STATUS_CODES[body];58 break;59 // string defaulting to html60 case 'string':61 if (!this.header('Content-Type')) {62 this.charset = this.charset || 'utf-8';63 this.contentType('.html');64 }65 break;66 case 'boolean':67 case 'object':68 if (null == body) {69 body = '';70 } else if (Buffer.isBuffer(body)) {71 this.header('Content-Type') || this.contentType('.bin');72 } else {73 return this.json(body);74 }75 break;76 }7778 // populate Content-Length79 if (undefined !== body && !this.header('Content-Length')) {80 this.header('Content-Length', Buffer.isBuffer(body)81 ? body.length82 : Buffer.byteLength(body));83 }8485 // strip irrelevant headers86 if (204 == this.statusCode || 304 == this.statusCode) {87 this.removeHeader('Content-Type');88 this.removeHeader('Content-Length');89 body = '';90 }9192 // respond93 this.end(head ? null : body);94 return this;95};9697/**98 * Send JSON response.99 *100 * Examples:101 *102 * res.json(null);103 * res.json({ user: 'tj' });104 * res.json(500, 'oh noes!');105 * res.json(404, 'I dont have that');106 *107 * @param {Mixed} obj or status108 * @param {Mixed} obj109 * @return {ServerResponse}110 * @api public111 */112113res.json = function(obj){114 // allow status / body115 if (2 == arguments.length) {116 this.statusCode = obj;117 obj = arguments[1];118 }119120 var body = JSON.stringify(obj)121 , callback = this.req.query.callback122 , jsonp = this.app.enabled('jsonp callback');123124 this.charset = this.charset || 'utf-8';125 this.header('Content-Type', 'application/json');126127 if (callback && jsonp) {128 this.header('Content-Type', 'text/javascript');129 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';130 }131132 return this.send(body);133};134135/**136 * Set status `code`.137 *138 * @param {Number} code139 * @return {ServerResponse}140 * @api public141 */142143res.status = function(code){144 this.statusCode = code;145 return this;146};147148/**149 * Transfer the file at the given `path`.150 * 151 * Automatically sets the _Content-Type_ response header field.152 * The callback `fn(err)` is invoked when the transfer is complete153 * or when an error occurs. Be sure to check `res.sentHeader`154 * if you wish to attempt responding, as the header and some data155 * may have already been transferred.156 *157 * Options:158 *159 * - `maxAge` defaulting to 0160 * - `root` root directory for relative filenames161 *162 * @param {String} path163 * @param {Object|Function} options or fn164 * @param {Function} fn165 * @api public166 */167168res.sendfile = function(path, options, fn){169 var self = this170 , req = self.req171 , next = this.req.next172 , options = options || {};173174 // support function as second arg175 if ('function' == typeof options) {176 fn = options;177 options = {};178 }179180 // callback181 options.callback = function(err){182 // TODO: remove when node adds this183 self.sentHeader = !! self._header;184185 // error186 if (err) {187 // ditch content-disposition to prevent funky responses188 if (!self.sentHeader) self.removeHeader('Content-Disposition');189190 // not found191 if ('ENOENT' == err.code) return req.next();192193 // lost in limbo if there's no callback194 if (self.sentHeader) return fn && fn(err);195196 // callback available197 if (fn) return fn(err);198199 return req.next(err);200 }201202 fn && fn();203 };204205 // transfer206 options.path = encodeURIComponent(path);207 send(this.req, this, next, options);208};209210/**211 * Transfer the file at the given `path` as an attachment.212 *213 * Optionally providing an alternate attachment `filename`,214 * and optional callback `fn(err)`. The callback is invoked215 * when the data transfer is complete, or when an error has216 * ocurred. Be sure to check `res.sendHeader` if you plan to respond.217 *218 * @param {String} path219 * @param {String|Function} filename or fn220 * @param {Function} fn221 * @api public222 */223224res.download = function(path, filename, fn){225 // support function as second arg226 if ('function' == typeof filename) {227 fn = filename;228 filename = null;229 }230231 return this.attachment(filename || path).sendfile(path, fn);232};233234/**235 * Set _Content-Type_ response header passed through `mime.lookup()`.236 *237 * Examples:238 *239 * var filename = 'path/to/image.png';240 * res.contentType(filename);241 * // res.headers['Content-Type'] is now "image/png"242 *243 * res.contentType('.html');244 * res.contentType('html');245 * res.contentType('json');246 * res.contentType('png');247 *248 * @param {String} type249 * @return {ServerResponse} for chaining250 * @api public251 */252253res.contentType = function(type){254 return this.header('Content-Type', mime.lookup(type));255};256257/**258 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.259 *260 * @param {String} filename261 * @return {ServerResponse}262 * @api public263 */264265res.attachment = function(filename){266 if (filename) this.contentType(filename);267 this.header('Content-Disposition', filename268 ? 'attachment; filename="' + basename(filename) + '"'269 : 'attachment');270 return this;271};272273/**274 * Set header `field` to `val`.275 *276 * @param {String} field277 * @param {String} val278 * @return {ServerResponse} for chaining279 * @api public280 */281282res.set = function(field, val){283 this.setHeader(field, val);284 return this;285};286287/**288 * Get value for header `field`.289 *290 * @param {String} field291 * @return {String}292 * @api public293 */294295res.get = function(field){296 return this.getHeader(field);297};298299/**300 * Set or get response header `field` with optional `val`.301 *302 * @param {String} name303 * @param {String} val304 * @return {ServerResponse} for chaining305 * @api public306 */307308res.header = function(field, val){309 if (1 == arguments.length) return this.getHeader(field);310 this.setHeader(field, val);311 return this;312};313314/**315 * Clear cookie `name`.316 *317 * @param {String} name318 * @param {Object} options319 * @param {ServerResponse} for chaining320 * @api public321 */322323res.clearCookie = function(name, options){324 var opts = { expires: new Date(1) };325 return this.cookie(name, '', options326 ? utils.merge(options, opts)327 : opts);328};329330/**331 * Set cookie `name` to `val`, with the given `options`.332 *333 * Options:334 *335 * - `maxAge` max-age in milliseconds, converted to `expires`336 * - `path` defaults to the "basepath" setting which is typically "/"337 *338 * Examples:339 *340 * // "Remember Me" for 15 minutes341 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });342 *343 * // save as above344 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })345 *346 * @param {String} name347 * @param {String} val348 * @param {Options} options349 * @api public350 */351352res.cookie = function(name, val, options){353 options = options || {};354 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);355 if (undefined === options.path) options.path = this.app.set('basepath');356 var cookie = utils.serializeCookie(name, val, options);357 this.header('Set-Cookie', cookie);358 return this;359};360361/**362 * Redirect to the given `url` with optional response `status`363 * defauling to 302.364 *365 * The given `url` can also be the name of a mapped url, for366 * example by default express supports "back" which redirects367 * to the _Referrer_ or _Referer_ headers or the application's368 * "basepath" setting. Express also supports "basepath" out of the box,369 * which can be set via `app.set('basepath', '/blog');`.370 *371 * Redirect Mapping:372 * 373 * To extend the redirect mapping capabilities that Express provides,374 * we may use the `app.redirect()` method:375 * 376 * app.redirect('google', 'http://google.com');377 * 378 * Now in a route we may call:379 *380 * res.redirect('google');381 *382 * We may also map dynamic redirects:383 *384 * app.redirect('comments', function(req, res){385 * return '/post/' + req.params.id + '/comments';386 * });387 *388 * So now we may do the following, and the redirect will dynamically adjust to389 * the context of the request. If we called this route with _GET /post/12_ our390 * redirect _Location_ would be _/post/12/comments_.391 *392 * app.get('/post/:id', function(req, res){393 * res.redirect('comments');394 * });395 *396 * Unless an absolute `url` is given, the app's mount-point397 * will be respected. For example if we redirect to `/posts`,398 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.399 *400 * @param {String} url401 * @param {Number} code402 * @api public403 */404405res.redirect = function(url, status){406 var app = this.app407 , req = this.req408 , base = app.set('basepath') || app.route409 , status = status || 302410 , body;411412 // Setup redirect map413 var map = {414 back: req.header('Referrer', base)415 , home: base416 };417418 // Support custom redirect map419 map.__proto__ = app.redirects;420421 // Attempt mapped redirect422 var mapped = 'function' == typeof map[url]423 ? map[url](req, this)424 : map[url];425426 // Perform redirect427 url = mapped || url;428429 // Relative430 if (!~url.indexOf('://')) {431 // Respect mount-point432 if ('/' != base && 0 != url.indexOf(base)) url = base + url;433434 // Absolute435 var host = req.headers.host436 , tls = req.connection.encrypted;437 url = 'http' + (tls ? 's' : '') + '://' + host + url;438 }439440 // Support text/{plain,html} by default441 if (req.accepts('html')) {442 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';443 this.header('Content-Type', 'text/html');444 } else {445 body = statusCodes[status] + '. Redirecting to ' + url;446 this.header('Content-Type', 'text/plain');447 }448449 // Respond450 this.statusCode = status;451 this.header('Location', url);452 this.end(body);453};