response.js
This file
Path
lib/response.js
405 lines · 9.5 KiB · JavaScript
Last changed by
Added res.send(bool) supportTj Holowaychukbefore adoptionb7232f3
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 , parseRange = require('./utils').parseRange18 , res = http.ServerResponse.prototype19 , send = connect.static.send20 , join = require('path').join21 , mime = require('mime');2223/**24 * Send a response with the given `body` and optional `headers` and `status` code.25 *26 * Examples:27 *28 * res.send();29 * res.send(new Buffer('wahoo'));30 * res.send({ some: 'json' });31 * res.send('<p>some html</p>');32 * res.send('Sorry, cant find that', 404);33 * res.send('text', { 'Content-Type': 'text/plain' }, 201);34 * res.send(404);35 *36 * @param {String|Object|Number|Buffer} body or status37 * @param {Object|Number} headers or status38 * @param {Number} status39 * @return {ServerResponse}40 * @api public41 */4243res.send = function(body, headers, status){44 // allow status as second arg45 if ('number' == typeof headers) {46 status = headers,47 headers = null;48 }4950 // default status51 status = status || this.statusCode;5253 // allow 0 args as 20454 if (!arguments.length) body = status = 204;5556 // determine content type57 switch (typeof body) {58 case 'number':59 if (!this.header('Content-Type')) {60 this.contentType('.txt');61 }62 body = http.STATUS_CODES[status = body];63 break;64 case 'string':65 if (!this.header('Content-Type')) {66 this.charset = this.charset || 'utf-8';67 this.contentType('.html');68 }69 break;70 case 'boolean':71 case 'object':72 if (Buffer.isBuffer(body)) {73 if (!this.header('Content-Type')) {74 this.contentType('.bin');75 }76 } else {77 if (!this.header('Content-Type')) {78 this.contentType('.json');79 }80 body = JSON.stringify(body);81 if (this.req.query.callback && this.app.set('jsonp callback')) {82 this.header('Content-Type', 'text/javascript');83 body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';84 }85 }86 break;87 }8889 // populate Content-Length90 if (!this.header('Content-Length')) {91 this.header('Content-Length', Buffer.isBuffer(body)92 ? body.length93 : Buffer.byteLength(body));94 }9596 // merge headers passed97 if (headers) {98 var fields = Object.keys(headers);99 for (var i = 0, len = fields.length; i < len; ++i) {100 var field = fields[i];101 this.header(field, headers[field]);102 }103 }104105 // strip irrelevant headers106 if (204 === status) {107 this.removeHeader('Content-Type');108 this.removeHeader('Content-Length');109 }110111 // respond112 this.statusCode = status;113 this.end('HEAD' == this.req.method ? undefined : body);114};115116/**117 * Transfer the file at the given `path`. Automatically sets 118 * the _Content-Type_ response header field. `next()` is called119 * when `path` is a directory, or when an error occurs.120 *121 * Options:122 *123 * - `maxAge` defaulting to 0124 * - `root` root directory for relative filenames125 *126 * @param {String} path127 * @param {Object|Function} options or fn128 * @param {Function} fn129 * @api public130 */131132res.sendfile = function(path, options, fn){133 options = options || {};134135 // support function as second arg136 if ('function' == typeof options) {137 fn = options;138 options = {};139 }140141 options.path = path;142 options.callback = fn;143 send(this.req, this, this.req.next, options);144};145146/**147 * Set _Content-Type_ response header passed through `mime.lookup()`.148 *149 * Examples:150 *151 * var filename = 'path/to/image.png';152 * res.contentType(filename);153 * // res.headers['Content-Type'] is now "image/png"154 *155 * res.contentType('.html');156 * res.contentType('html');157 * res.contentType('json');158 * res.contentType('png');159 *160 * @param {String} type161 * @return {String} the resolved mime type162 * @api public163 */164165res.contentType = function(type){166 return this.header('Content-Type', mime.lookup(type));167};168169/**170 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.171 *172 * @param {String} filename173 * @return {ServerResponse}174 * @api public175 */176177res.attachment = function(filename){178 this.header('Content-Disposition', filename179 ? 'attachment; filename="' + path.basename(filename) + '"'180 : 'attachment');181 return this;182};183184/**185 * Transfer the file at the given `path`, with optional 186 * `filename` as an attachment and optional callback `fn(err)`.187 *188 * @param {String} path189 * @param {String|Function} filename or fn190 * @param {Function} fn191 * @return {Type}192 * @api public193 */194195res.download = function(path, filename, fn){196 var self = this;197198 // support callback as second arg199 if ('function' == typeof filename) {200 fn = filename;201 filename = null;202 }203204 // transfer the file205 this.attachment(filename || path).sendfile(path, function(err){206 if (err) self.removeHeader('Content-Disposition');207 if (fn) return fn(err);208 if (err) {209 self.req.next('ENOENT' == err.code210 ? null211 : err);212 }213 });214};215216/**217 * Set or get response header `name` with optional `val`.218 *219 * @param {String} name220 * @param {String} val221 * @return {String}222 * @api public223 */224225res.header = function(name, val){226 if (val === undefined) {227 return this.getHeader(name);228 } else {229 this.setHeader(name, val);230 return val;231 }232};233234/**235 * Clear cookie `name`.236 *237 * @param {String} name238 * @api public239 */240241res.clearCookie = function(name){242 this.cookie(name, '', { expires: new Date(1) });243};244245/**246 * Set cookie `name` to `val`, with the given `options`.247 *248 * Options:249 *250 * - `maxAge` max-age in milliseconds, converted to `expires`251 *252 * Examples:253 *254 * // "Remember Me" for 15 minutes255 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });256 *257 * // save as above258 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })259 *260 * @param {String} name261 * @param {String} val262 * @param {Options} options263 * @api public264 */265266res.cookie = function(name, val, options){267 options = options || {};268 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);269 var cookie = utils.serializeCookie(name, val, options);270 this.header('Set-Cookie', cookie);271};272273/**274 * Redirect to the given `url` with optional response `status`275 * defauling to 302.276 *277 * The given `url` can also be the name of a mapped url, for278 * example by default express supports "back" which redirects279 * to the _Referrer_ or _Referer_ headers or the application's280 * "home" setting. Express also supports "home" out of the box,281 * which can be set via `app.set('home', '/blog');`, and defaults282 * to '/'.283 *284 * Redirect Mapping:285 * 286 * To extend the redirect mapping capabilities that Express provides,287 * we may use the `app.redirect()` method:288 * 289 * app.redirect('google', 'http://google.com');290 * 291 * Now in a route we may call:292 *293 * res.redirect('google');294 *295 * We may also map dynamic redirects:296 *297 * app.redirect('comments', function(req, res){298 * return '/post/' + req.params.id + '/comments';299 * });300 *301 * So now we may do the following, and the redirect will dynamically adjust to302 * the context of the request. If we called this route with _GET /post/12_ our303 * redirect _Location_ would be _/post/12/comments_.304 *305 * app.get('/post/:id', function(req, res){306 * res.redirect('comments');307 * });308 *309 * Unless an absolute `url` is given, the app's mount-point310 * will be respected. For example if we redirect to `/posts`,311 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.312 *313 * @param {String} url314 * @param {Number} code315 * @api public316 */317318res.redirect = function(url, status){319 var app = this.app320 , req = this.req321 , base = app.set('home') || '/'322 , status = status || 302323 , body;324325 // Setup redirect map326 var map = {327 back: req.header('Referrer', base)328 , home: base329 };330331 // Support custom redirect map332 map.__proto__ = app.redirects;333334 // Attempt mapped redirect335 var mapped = 'function' == typeof map[url]336 ? map[url](req, this)337 : map[url];338339 // Perform redirect340 url = mapped || url;341342 // Relative343 if (!~url.indexOf('://')) {344 // Respect mount-point345 if (app.route) {346 url = join(app.route, url);347 }348349 // Absolute350 var host = req.headers.host351 , tls = req.connection.encrypted;352 url = 'http' + (tls ? 's' : '') + '://' + host + url;353 }354 355356 // Support text/{plain,html} by default357 if (req.accepts('html')) {358 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';359 this.header('Content-Type', 'text/html');360 } else {361 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;362 this.header('Content-Type', 'text/plain');363 }364365 // Respond366 this.statusCode = status;367 this.header('Location', url);368 this.end(body);369};370371/**372 * Assign the view local variable `name` to `val` or return the373 * local previously assigned to `name`.374 *375 * @param {String} name376 * @param {Mixed} val377 * @return {Mixed} val378 * @api public379 */380381res.local = function(name, val){382 this._locals = this._locals || {};383 return undefined === val384 ? this._locals[name]385 : this._locals[name] = val;386};387388/**389 * Assign several locals with the given `obj`,390 * or return the locals.391 *392 * @param {Object} obj393 * @return {Object|Undefined}394 * @api public395 */396397res.locals = function(obj){398 if (obj) {399 for (var key in obj) {400 this.local(key, obj[key]);401 }402 } else {403 return this._locals;404 }405};