response.js
This file
Path
lib/response.js
404 lines · 9.5 KiB · JavaScript
Last changed by
refactored res.redirect()Tj Holowaychukbefore adoption9c9e2af
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 'object':71 if (Buffer.isBuffer(body)) {72 if (!this.header('Content-Type')) {73 this.contentType('.bin');74 }75 } else {76 if (!this.header('Content-Type')) {77 this.contentType('.json');78 }79 body = JSON.stringify(body);80 if (this.req.query.callback && this.app.set('jsonp callback')) {81 this.header('Content-Type', 'text/javascript');82 body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';83 }84 }85 break;86 }8788 // populate Content-Length89 if (!this.header('Content-Length')) {90 this.header('Content-Length', Buffer.isBuffer(body)91 ? body.length92 : Buffer.byteLength(body));93 }9495 // merge headers passed96 if (headers) {97 var fields = Object.keys(headers);98 for (var i = 0, len = fields.length; i < len; ++i) {99 var field = fields[i];100 this.header(field, headers[field]);101 }102 }103104 // strip irrelevant headers105 if (204 === status) {106 this.removeHeader('Content-Type');107 this.removeHeader('Content-Length');108 }109110 // respond111 this.statusCode = status;112 this.end('HEAD' == this.req.method ? undefined : body);113};114115/**116 * Transfer the file at the given `path`. Automatically sets 117 * the _Content-Type_ response header field. `next()` is called118 * when `path` is a directory, or when an error occurs.119 *120 * Options:121 *122 * - `maxAge` defaulting to 0123 * - `root` root directory for relative filenames124 *125 * @param {String} path126 * @param {Object|Function} options or fn127 * @param {Function} fn128 * @api public129 */130131res.sendfile = function(path, options, fn){132 options = options || {};133134 // support function as second arg135 if ('function' == typeof options) {136 fn = options;137 options = {};138 }139140 options.path = path;141 options.callback = fn;142 send(this.req, this, this.req.next, options);143};144145/**146 * Set _Content-Type_ response header passed through `mime.lookup()`.147 *148 * Examples:149 *150 * var filename = 'path/to/image.png';151 * res.contentType(filename);152 * // res.headers['Content-Type'] is now "image/png"153 *154 * res.contentType('.html');155 * res.contentType('html');156 * res.contentType('json');157 * res.contentType('png');158 *159 * @param {String} type160 * @return {String} the resolved mime type161 * @api public162 */163164res.contentType = function(type){165 return this.header('Content-Type', mime.lookup(type));166};167168/**169 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.170 *171 * @param {String} filename172 * @return {ServerResponse}173 * @api public174 */175176res.attachment = function(filename){177 this.header('Content-Disposition', filename178 ? 'attachment; filename="' + path.basename(filename) + '"'179 : 'attachment');180 return this;181};182183/**184 * Transfer the file at the given `path`, with optional 185 * `filename` as an attachment and optional callback `fn(err)`.186 *187 * @param {String} path188 * @param {String|Function} filename or fn189 * @param {Function} fn190 * @return {Type}191 * @api public192 */193194res.download = function(path, filename, fn){195 var self = this;196197 // support callback as second arg198 if ('function' == typeof filename) {199 fn = filename;200 filename = null;201 }202203 // transfer the file204 this.attachment(filename || path).sendfile(path, function(err){205 if (err) self.removeHeader('Content-Disposition');206 if (fn) return fn(err);207 if (err) {208 self.req.next('ENOENT' == err.code209 ? null210 : err);211 }212 });213};214215/**216 * Set or get response header `name` with optional `val`.217 *218 * @param {String} name219 * @param {String} val220 * @return {String}221 * @api public222 */223224res.header = function(name, val){225 if (val === undefined) {226 return this.getHeader(name);227 } else {228 this.setHeader(name, val);229 return val;230 }231};232233/**234 * Clear cookie `name`.235 *236 * @param {String} name237 * @api public238 */239240res.clearCookie = function(name){241 this.cookie(name, '', { expires: new Date(1) });242};243244/**245 * Set cookie `name` to `val`, with the given `options`.246 *247 * Options:248 *249 * - `maxAge` max-age in milliseconds, converted to `expires`250 *251 * Examples:252 *253 * // "Remember Me" for 15 minutes254 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });255 *256 * // save as above257 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })258 *259 * @param {String} name260 * @param {String} val261 * @param {Options} options262 * @api public263 */264265res.cookie = function(name, val, options){266 options = options || {};267 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);268 var cookie = utils.serializeCookie(name, val, options);269 this.header('Set-Cookie', cookie);270};271272/**273 * Redirect to the given `url` with optional response `status`274 * defauling to 302.275 *276 * The given `url` can also be the name of a mapped url, for277 * example by default express supports "back" which redirects278 * to the _Referrer_ or _Referer_ headers or the application's279 * "home" setting. Express also supports "home" out of the box,280 * which can be set via `app.set('home', '/blog');`, and defaults281 * to '/'.282 *283 * Redirect Mapping:284 * 285 * To extend the redirect mapping capabilities that Express provides,286 * we may use the `app.redirect()` method:287 * 288 * app.redirect('google', 'http://google.com');289 * 290 * Now in a route we may call:291 *292 * res.redirect('google');293 *294 * We may also map dynamic redirects:295 *296 * app.redirect('comments', function(req, res){297 * return '/post/' + req.params.id + '/comments';298 * });299 *300 * So now we may do the following, and the redirect will dynamically adjust to301 * the context of the request. If we called this route with _GET /post/12_ our302 * redirect _Location_ would be _/post/12/comments_.303 *304 * app.get('/post/:id', function(req, res){305 * res.redirect('comments');306 * });307 *308 * Unless an absolute `url` is given, the app's mount-point309 * will be respected. For example if we redirect to `/posts`,310 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.311 *312 * @param {String} url313 * @param {Number} code314 * @api public315 */316317res.redirect = function(url, status){318 var app = this.app319 , req = this.req320 , base = app.set('home') || '/'321 , status = status || 302322 , body;323324 // Setup redirect map325 var map = {326 back: req.header('Referrer', base)327 , home: base328 };329330 // Support custom redirect map331 map.__proto__ = app.redirects;332333 // Attempt mapped redirect334 var mapped = 'function' == typeof map[url]335 ? map[url](req, this)336 : map[url];337338 // Perform redirect339 url = mapped || url;340341 // Relative342 if (!~url.indexOf('://')) {343 // Respect mount-point344 if (app.route) {345 url = join(app.route, url);346 }347348 // Absolute349 var host = req.headers.host350 , tls = req.connection.encrypted;351 url = 'http' + (tls ? 's' : '') + '://' + host + url;352 }353 354355 // Support text/{plain,html} by default356 if (req.accepts('html')) {357 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';358 this.header('Content-Type', 'text/html');359 } else {360 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;361 this.header('Content-Type', 'text/plain');362 }363364 // Respond365 this.statusCode = status;366 this.header('Location', url);367 this.end(body);368};369370/**371 * Assign the view local variable `name` to `val` or return the372 * local previously assigned to `name`.373 *374 * @param {String} name375 * @param {Mixed} val376 * @return {Mixed} val377 * @api public378 */379380res.local = function(name, val){381 this._locals = this._locals || {};382 return undefined === val383 ? this._locals[name]384 : this._locals[name] = val;385};386387/**388 * Assign several locals with the given `obj`,389 * or return the locals.390 *391 * @param {Object} obj392 * @return {Object|Undefined}393 * @api public394 */395396res.locals = function(obj){397 if (obj) {398 for (var key in obj) {399 this.local(key, obj[key]);400 }401 } else {402 return this._locals;403 }404};