response.js
This file
Path
lib/response.js
404 lines · 9.5 KiB · JavaScript
Last changed by
Merge branch 'remove-header-fields'Tj Holowaychukbefore adoption772c135
History of this fileTake it
The walk stopped after 200 commits: lines older than e0bc571 point at it.
auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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;auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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.auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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){auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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';auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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);auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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) {auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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);auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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};135auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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);auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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) + '"'auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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.auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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);auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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 chainingauto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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) {auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
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;auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
lines 262–268why, one step back262 }263};264265/**266 * Clear cookie `name`.267 *268 * @param {String} nameAdded options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
line 269why, one step back269 * @param {Object} optionsauto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
lines 270–272why, one step back270 * @api public271 */272Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 273–277why, one step back273res.clearCookie = function(name, options){274 var opts = { expires: new Date(1) };275 this.cookie(name, '', options276 ? utils.merge(options, opts)277 : opts);auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
lines 278–285why, one step back278};279280/**281 * Set cookie `name` to `val`, with the given `options`.282 *283 * Options:284 *285 * - `maxAge` max-age in milliseconds, converted to `expires`Changed; default cookie path to "home" setting. Closes #731Tj Holowaychukbefore adoption09c9452
line 286why, one step back286 * - `path` defaults to the "home" setting which is typically "/"auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
lines 287–304why, one step back287 *288 * Examples:289 *290 * // "Remember Me" for 15 minutes291 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });292 *293 * // save as above294 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })295 *296 * @param {String} name297 * @param {String} val298 * @param {Options} options299 * @api public300 */301302res.cookie = function(name, val, options){303 options = options || {};304 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);when cookie path === null dont default itTj Holowaychukbefore adoptionee4471b
line 305why, one step back305 if (undefined === options.path) options.path = this.app.set('home');auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
lines 306–381why, one step back306 var cookie = utils.serializeCookie(name, val, options);307 this.header('Set-Cookie', cookie);308};309310/**311 * Redirect to the given `url` with optional response `status`312 * defauling to 302.313 *314 * The given `url` can also be the name of a mapped url, for315 * example by default express supports "back" which redirects316 * to the _Referrer_ or _Referer_ headers or the application's317 * "home" setting. Express also supports "home" out of the box,318 * which can be set via `app.set('home', '/blog');`, and defaults319 * to '/'.320 *321 * Redirect Mapping:322 * 323 * To extend the redirect mapping capabilities that Express provides,324 * we may use the `app.redirect()` method:325 * 326 * app.redirect('google', 'http://google.com');327 * 328 * Now in a route we may call:329 *330 * res.redirect('google');331 *332 * We may also map dynamic redirects:333 *334 * app.redirect('comments', function(req, res){335 * return '/post/' + req.params.id + '/comments';336 * });337 *338 * So now we may do the following, and the redirect will dynamically adjust to339 * the context of the request. If we called this route with _GET /post/12_ our340 * redirect _Location_ would be _/post/12/comments_.341 *342 * app.get('/post/:id', function(req, res){343 * res.redirect('comments');344 * });345 *346 * Unless an absolute `url` is given, the app's mount-point347 * will be respected. For example if we redirect to `/posts`,348 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.349 *350 * @param {String} url351 * @param {Number} code352 * @api public353 */354355res.redirect = function(url, status){356 var app = this.app357 , req = this.req358 , base = app.set('home') || '/'359 , status = status || 302360 , body;361362 // Setup redirect map363 var map = {364 back: req.header('Referrer', base)365 , home: base366 };367368 // Support custom redirect map369 map.__proto__ = app.redirects;370371 // Attempt mapped redirect372 var mapped = 'function' == typeof map[url]373 ? map[url](req, this)374 : map[url];375376 // Perform redirect377 url = mapped || url;378379 // Relative380 if (!~url.indexOf('://')) {381 // Respect mount-pointmisc refactorTj Holowaychukbefore adoption490584c
line 382why, one step back382 if (app.route) url = join(app.route, url);auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
lines 383–404why, one step back383384 // Absolute385 var host = req.headers.host386 , tls = req.connection.encrypted;387 url = 'http' + (tls ? 's' : '') + '://' + host + url;388 }389 390391 // Support text/{plain,html} by default392 if (req.accepts('html')) {393 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';394 this.header('Content-Type', 'text/html');395 } else {396 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;397 this.header('Content-Type', 'text/plain');398 }399400 // Respond401 this.statusCode = status;402 this.header('Location', url);403 this.end(body);404};