response.js
This file
Path
lib/response.js
406 lines · 9.6 KiB · JavaScript
Last changed by
Changed `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8
History of this fileTake it
The walk stopped after 200 commits: lines older than dc02b0d point at it.
Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 1–19why, one step back12/*!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.sendmisc refactoringTj Holowaychukbefore adoption70e6baf
lines 20–22why, one step back20 , mime = require('mime')21 , basename = path.basename22 , join = path.join;Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 23–24why, one step back2324/**Merge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
line 25why, one step back25 * Send a response with the given `body` and optional `status` code.Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 26–40why, one step back26 *27 * Examples:28 *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(404);34 *35 * @param {String|Object|Number|Buffer} body or status36 * @param {Number} status37 * @return {ServerResponse}38 * @api public39 */40Merge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
line 41why, one step back41res.send = function(body, status){Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 42–54why, one step back42 // default status43 status = status || this.statusCode;4445 // determine content type46 switch (typeof body) {47 case 'number':48 if (!this.header('Content-Type')) {49 this.contentType('.txt');50 }51 body = http.STATUS_CODES[status = body];52 break;53 case 'string':54 if (!this.header('Content-Type')) {JSON and JSONP default to UTF-8 in the same way as HTML. Closes #632.Daniel Shawbefore adoption3afbcd0
line 55why, one step back55 this.charset = this.charset || 'utf-8';Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 56–65why, one step back56 this.contentType('.html');57 }58 break;59 case 'boolean':60 case 'object':61 if (Buffer.isBuffer(body)) {62 if (!this.header('Content-Type')) {63 this.contentType('.bin');64 }65 } else {Merge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
line 66why, one step back66 return this.json(body, status);Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 67–78why, one step back67 }68 break;69 }7071 // populate Content-Length72 if (!this.header('Content-Length')) {73 this.header('Content-Length', Buffer.isBuffer(body)74 ? body.length75 : Buffer.byteLength(body));76 }7778 // strip irrelevant headersFixed; ignore body on 304. Closes #701Tj Holowaychukbefore adoption9028cac
line 79why, one step back79 if (204 == status || 304 == status) {Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 80–86why, one step back80 this.removeHeader('Content-Type');81 this.removeHeader('Content-Length');82 }8384 // respond85 this.statusCode = status;86 this.end('HEAD' == this.req.method ? undefined : body);Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 87–90why, one step back87 return this;88};8990/**Merge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
line 91why, one step back91 * Send JSON response with `obj` and optional `status`.Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 92–101why, one step back92 *93 * Examples:94 *95 * res.json(null);96 * res.json({ user: 'tj' });97 * res.json('oh noes!', 500);98 * res.json('I dont have that', 404);99 *100 * @param {Mixed} obj101 * @param {Number} statusMerge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
line 102why, one step back102 * @param {Number} statusMerge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 103–106why, one step back103 * @return {ServerResponse}104 * @api public105 */106Merge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
line 107why, one step back107res.json = function(obj, status){Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 108–111why, one step back108 var body = JSON.stringify(obj)109 , callback = this.req.query.callback110 , jsonp = this.app.enabled('jsonp callback');111Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 112–113why, one step back112 this.charset = this.charset || 'utf-8';113 this.header('Content-Type', 'application/json');Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 114–116why, one step back114115 if (callback && jsonp) {116 this.header('Content-Type', 'text/javascript');Revert "removed jsonp stripping"Tj Holowaychukbefore adoption60d16ea
line 117why, one step back117 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 118–119why, one step back118 }119Merge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
line 120why, one step back120 return this.send(body, status);Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 121–122why, one step back121};122docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 123–130why, one step back123/**124 * Set status `code`.125 *126 * @param {Number} code127 * @return {ServerResponse}128 * @api public129 */130Added chainable res.status(code)Tj Holowaychukbefore adoptionb04be51
lines 131–135why, one step back131res.status = function(code){132 this.statusCode = code;133 return this;134};135Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 136–161why, one step back136/**137 * Transfer the file at the given `path`. Automatically sets 138 * the _Content-Type_ response header field. `next()` is called139 * when `path` is a directory, or when an error occurs.140 *141 * Options:142 *143 * - `maxAge` defaulting to 0144 * - `root` root directory for relative filenames145 *146 * @param {String} path147 * @param {Object|Function} options or fn148 * @param {Function} fn149 * @api public150 */151152res.sendfile = function(path, options, fn){153 var next = this.req.next;154 options = options || {};155156 // support function as second arg157 if ('function' == typeof options) {158 fn = options;159 options = {};160 }161Fixed res.sendfile() bug preventing the transfer of files with spacesTj Holowaychukbefore adoptionc6d7608
line 162why, one step back162 options.path = encodeURIComponent(path);Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 163–200why, one step back163 options.callback = fn;164 send(this.req, this, next, options);165};166167/**168 * Set _Content-Type_ response header passed through `mime.lookup()`.169 *170 * Examples:171 *172 * var filename = 'path/to/image.png';173 * res.contentType(filename);174 * // res.headers['Content-Type'] is now "image/png"175 *176 * res.contentType('.html');177 * res.contentType('html');178 * res.contentType('json');179 * res.contentType('png');180 *181 * @param {String} type182 * @return {String} the resolved mime type183 * @api public184 */185186res.contentType = function(type){187 return this.header('Content-Type', mime.lookup(type));188};189190/**191 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.192 *193 * @param {String} filename194 * @return {ServerResponse}195 * @api public196 */197198res.attachment = function(filename){199 if (filename) this.contentType(filename);200 this.header('Content-Disposition', filenamemisc refactoringTj Holowaychukbefore adoption70e6baf
line 201why, one step back201 ? 'attachment; filename="' + basename(filename) + '"'Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 202–209why, one step back202 : 'attachment');203 return this;204};205206/**207 * Transfer the file at the given `path`, with optional 208 * `filename` as an attachment and optional callback `fn(err)`,209 * and optional `fn2(err)` which is invoked when an error hastypoTj Holowaychukbefore adoption0cbb1f6
line 210why, one step back210 * occurred after header has been sent.Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 211–234why, one step back211 *212 * @param {String} path213 * @param {String|Function} filename or fn214 * @param {Function} fn215 * @param {Function} fn2216 * @api public217 */218219res.download = function(path, filename, fn, fn2){220 var self = this;221222 // support callback as second arg223 if ('function' == typeof filename) {224 fn2 = fn;225 fn = filename;226 filename = null;227 }228229 // transfer the file230 this.attachment(filename || path).sendfile(path, function(err){231 var sentHeader = self._header;232 if (err) {233 if (!sentHeader) self.removeHeader('Content-Disposition');234 if (sentHeader) {misc refactorTj Holowaychukbefore adoptionaa68581
line 235why, one step back235 fn2 && fn2(err);Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 236–251why, one step back236 } else if (fn) {237 fn(err);238 } else {239 self.req.next(err);240 }241 } else if (fn) {242 fn();243 }244 });245};246247/**248 * Set or get response header `name` with optional `val`.249 *250 * @param {String} name251 * @param {String} valMerge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
line 252why, one step back252 * @return {ServerResponse} for chainingAdded options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 253–256why, one step back253 * @api public254 */255256res.header = function(name, val){Merge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
line 257why, one step back257 if (1 == arguments.length) {Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 258–260why, one step back258 return this.getHeader(name);259 } else {260 this.setHeader(name, val);Merge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
line 261why, one step back261 return this;Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 262–269why, one step back262 }263};264265/**266 * Clear cookie `name`.267 *268 * @param {String} name269 * @param {Object} optionsChanged `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8
line 270why, one step back270 * @param {ServerResponse} for chainingAdded options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 271–275why, one step back271 * @api public272 */273274res.clearCookie = function(name, options){275 var opts = { expires: new Date(1) };Changed `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8
line 276why, one step back276 return this.cookie(name, '', optionsAdded options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 277–286why, one step back277 ? utils.merge(options, opts)278 : opts);279};280281/**282 * Set cookie `name` to `val`, with the given `options`.283 *284 * Options:285 *286 * - `maxAge` max-age in milliseconds, converted to `expires`Changed; default cookie path to "home" setting. Closes #731Tj Holowaychukbefore adoption09c9452
line 287why, one step back287 * - `path` defaults to the "home" setting which is typically "/"Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 288–305why, one step back288 *289 * Examples:290 *291 * // "Remember Me" for 15 minutes292 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });293 *294 * // save as above295 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })296 *297 * @param {String} name298 * @param {String} val299 * @param {Options} options300 * @api public301 */302303res.cookie = function(name, val, options){304 options = options || {};305 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);when cookie path === null dont default itTj Holowaychukbefore adoptionee4471b
line 306why, one step back306 if (undefined === options.path) options.path = this.app.set('home');Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 307–308why, one step back307 var cookie = utils.serializeCookie(name, val, options);308 this.header('Set-Cookie', cookie);Changed `res.{cookie,clearCookie}()` return resTj Holowaychukbefore adoptiona3cddb8
line 309why, one step back309 return this;Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 310–383why, one step back310};311312/**313 * Redirect to the given `url` with optional response `status`314 * defauling to 302.315 *316 * The given `url` can also be the name of a mapped url, for317 * example by default express supports "back" which redirects318 * to the _Referrer_ or _Referer_ headers or the application's319 * "home" setting. Express also supports "home" out of the box,320 * which can be set via `app.set('home', '/blog');`, and defaults321 * to '/'.322 *323 * Redirect Mapping:324 * 325 * To extend the redirect mapping capabilities that Express provides,326 * we may use the `app.redirect()` method:327 * 328 * app.redirect('google', 'http://google.com');329 * 330 * Now in a route we may call:331 *332 * res.redirect('google');333 *334 * We may also map dynamic redirects:335 *336 * app.redirect('comments', function(req, res){337 * return '/post/' + req.params.id + '/comments';338 * });339 *340 * So now we may do the following, and the redirect will dynamically adjust to341 * the context of the request. If we called this route with _GET /post/12_ our342 * redirect _Location_ would be _/post/12/comments_.343 *344 * app.get('/post/:id', function(req, res){345 * res.redirect('comments');346 * });347 *348 * Unless an absolute `url` is given, the app's mount-point349 * will be respected. For example if we redirect to `/posts`,350 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.351 *352 * @param {String} url353 * @param {Number} code354 * @api public355 */356357res.redirect = function(url, status){358 var app = this.app359 , req = this.req360 , base = app.set('home') || '/'361 , status = status || 302362 , body;363364 // Setup redirect map365 var map = {366 back: req.header('Referrer', base)367 , home: base368 };369370 // Support custom redirect map371 map.__proto__ = app.redirects;372373 // Attempt mapped redirect374 var mapped = 'function' == typeof map[url]375 ? map[url](req, this)376 : map[url];377378 // Perform redirect379 url = mapped || url;380381 // Relative382 if (!~url.indexOf('://')) {383 // Respect mount-pointmisc refactorTj Holowaychukbefore adoption490584c
line 384why, one step back384 if (app.route) url = join(app.route, url);Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 385–406why, one step back385386 // Absolute387 var host = req.headers.host388 , tls = req.connection.encrypted;389 url = 'http' + (tls ? 's' : '') + '://' + host + url;390 }391 392393 // Support text/{plain,html} by default394 if (req.accepts('html')) {395 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';396 this.header('Content-Type', 'text/html');397 } else {398 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;399 this.header('Content-Type', 'text/plain');400 }401402 // Respond403 this.statusCode = status;404 this.header('Location', url);405 this.end(body);406};