response.js
This file
Path
lib/response.js
374 lines · 9.0 KiB · JavaScript
Last changed by
Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
History of this fileTake it
moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 1–14why, 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')refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
lines 15–16why, one step back15 , connect = require('connect')16 , utils = connect.utilsmoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 17why, one step back17 , parseRange = require('./utils').parseRangeusing Stream#pipe() instead of sys.pump()Tj Holowaychukbefore adoption0e790e6
line 18why, one step back18 , res = http.ServerResponse.prototyperefactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 19why, one step back19 , send = connect.static.sendMerge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 20why, one step back20 , join = require('path').joinreplaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85
line 21why, one step back21 , mime = require('mime');moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 22–42why, one step back2223/**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 */42Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 43why, one step back43res.send = function(body, headers, status){refactored res.send()Tj Holowaychukbefore adoption3661922
line 44why, one step back44 // allow status as second argstylingTj Holowaychukbefore adoption770f05c
line 45why, one step back45 if ('number' == typeof headers) {moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 46–49why, one step back46 status = headers,47 headers = null;48 }49refactored res.send()Tj Holowaychukbefore adoption3661922
lines 50–51why, one step back50 // default status51 status = status || this.statusCode;moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 52why, one step back52refactored res.send()Tj Holowaychukbefore adoption3661922
line 53why, one step back53 // allow 0 args as 204Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 54why, one step back54 if (!arguments.length) body = status = 204;moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 55why, one step back55refactored res.send()Tj Holowaychukbefore adoption3661922
line 56why, one step back56 // determine content typemoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 57–58why, one step back57 switch (typeof body) {58 case 'number':Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 59why, one step back59 if (!this.header('Content-Type')) {moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 60–64why, one step back60 this.contentType('.txt');61 }62 body = http.STATUS_CODES[status = body];63 break;64 case 'string':Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 65why, one step back65 if (!this.header('Content-Type')) {moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 66–70why, one step back66 this.contentType('.html');67 }68 break;69 case 'object':70 if (body instanceof Buffer) {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 71why, one step back71 if (!this.header('Content-Type')) {moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 72–74why, one step back72 this.contentType('.bin');73 }74 } else {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 75why, one step back75 if (!this.header('Content-Type')) {moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 76–78why, one step back76 this.contentType('.json');77 }78 body = JSON.stringify(body);Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 79why, one step back79 if (this.req.query.callback && this.app.set('jsonp callback')) {moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 80–86why, one step back80 this.header('Content-Type', 'text/javascript');81 body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';82 }83 }84 break;85 }86refactored res.send()Tj Holowaychukbefore adoption3661922
line 87why, one step back87 // populate Content-LengthMerge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 88why, one step back88 if (!this.header('Content-Length')) {moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 89–93why, one step back89 this.header('Content-Length', body instanceof Buffer90 ? body.length91 : Buffer.byteLength(body));92 }93refactored res.send()Tj Holowaychukbefore adoption3661922
line 94why, one step back94 // merge headers passedmoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 95–102why, one step back95 if (headers) {96 var fields = Object.keys(headers);97 for (var i = 0, len = fields.length; i < len; ++i) {98 var field = fields[i];99 this.header(field, headers[field]);100 }101 }102refactored res.send()Tj Holowaychukbefore adoption3661922
line 103why, one step back103 // strip irrelevant headersmoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 104why, one step back104 if (204 === status) {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
lines 105–106why, one step back105 this.removeHeader('Content-Type');106 this.removeHeader('Content-Length');moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 107–108why, one step back107 }108refactored res.send()Tj Holowaychukbefore adoption3661922
lines 109–110why, one step back109 // respond110 this.statusCode = status;moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 111–115why, one step back111 this.end('HEAD' == this.req.method ? undefined : body);112};113114/**115 * Transfer the file at the given `path`. Automatically sets refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
lines 116–117why, one step back116 * the _Content-Type_ response header field. `next()` is called117 * when `path` is a directory, or when an error occurs.moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 118why, one step back118 *refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 119why, one step back119 * Options:moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 120why, one step back120 *refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
lines 121–123why, one step back121 * - `maxAge` defaulting to 0122 * - `root` root directory for relative filenames123 *moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 124why, one step back124 * @param {String} pathres.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
lines 125–126why, one step back125 * @param {Object|Function} options or fn126 * @param {Function} fnmoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 127–129why, one step back127 * @api public128 */129res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
line 130why, one step back130res.sendfile = function(path, options, fn){refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 131why, one step back131 options = options || {};res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
lines 132–138why, one step back132133 // support function as second arg134 if ('function' == typeof options) {135 fn = options;136 options = {};137 }138refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 139why, one step back139 options.path = path;res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
line 140why, one step back140 options.callback = fn;refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 141why, one step back141 send(this.req, this, this.req.next, options);moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 142–144why, one step back142};143144/**replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85
line 145why, one step back145 * Set _Content-Type_ response header passed through `mime.lookup()`.moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 146–162why, one step back146 *147 * Examples:148 *149 * var filename = 'path/to/image.png';150 * res.contentType(filename);151 * // res.headers['Content-Type'] is now "image/png"152 *153 * res.contentType('.html');154 * res.contentType('html');155 * res.contentType('json');156 * res.contentType('png');157 *158 * @param {String} type159 * @return {String} the resolved mime type160 * @api public161 */162Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 163why, one step back163res.contentType = function(type){replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85
line 164why, one step back164 return this.header('Content-Type', mime.lookup(type));moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 165–174why, one step back165};166167/**168 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.169 *170 * @param {String} filename171 * @return {ServerResponse}172 * @api public173 */174Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 175why, one step back175res.attachment = function(filename){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 176–183why, one step back176 this.header('Content-Disposition', filename177 ? 'attachment; filename="' + path.basename(filename) + '"'178 : 'attachment');179 return this;180};181182/**183 * Transfer the file at the given `path`, with optional res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
line 184why, one step back184 * `filename` as an attachment and optional callback `fn(err)`.moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 185–186why, one step back185 *186 * @param {String} pathres.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
lines 187–188why, one step back187 * @param {String|Function} filename or fn188 * @param {Function} fnmoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 189–192why, one step back189 * @return {Type}190 * @api public191 */192res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
lines 193–211why, one step back193res.download = function(path, filename, fn){194 var self = this;195196 // support callback as second arg197 if ('function' == typeof filename) {198 fn = filename;199 filename = null;200 }201202 // transfer the file203 this.attachment(filename || path).sendfile(path, function(err){204 if (err) self.removeHeader('Content-Disposition');205 if (fn) return fn(err);206 if (err) {207 self.req.next('ENOENT' == err.code208 ? null209 : err);210 }211 });moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 212–222why, one step back212};213214/**215 * Set or get response header `name` with optional `val`.216 *217 * @param {String} name218 * @param {String} val219 * @return {String}220 * @api public221 */222Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 223why, one step back223res.header = function(name, val){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 224why, one step back224 if (val === undefined) {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 225why, one step back225 return this.getHeader(name);moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 226why, one step back226 } else {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
lines 227–228why, one step back227 this.setHeader(name, val);228 return val;moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 229–238why, one step back229 }230};231232/**233 * Clear cookie `name`.234 *235 * @param {String} name236 * @api public237 */238Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 239why, one step back239res.clearCookie = function(name){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 240–243why, one step back240 this.cookie(name, '', { expires: new Date(1) });241};242243/**Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
line 244why, one step back244 * Set cookie `name` to `val`, with the given `options`.moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 245why, one step back245 *Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 246–249why, one step back246 * Options:247 *248 * - `maxAge` max-age in milliseconds, converted to `expires`249 *moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 250–254why, one step back250 * Examples:251 *252 * // "Remember Me" for 15 minutes253 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });254 *Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 255–257why, one step back255 * // save as above256 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })257 *moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 258–263why, one step back258 * @param {String} name259 * @param {String} val260 * @param {Options} options261 * @api public262 */263Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 264why, one step back264res.cookie = function(name, val, options){Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 265–266why, one step back265 options = options || {};266 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 267–303why, one step back267 var cookie = utils.serializeCookie(name, val, options);268 this.header('Set-Cookie', cookie);269};270271/**272 * Redirect to the given `url` with optional response `status`273 * defauling to 302.274 *275 * The given `url` can also be the name of a mapped url, for276 * example by default express supports "back" which redirects277 * to the _Referrer_ or _Referer_ headers or the application's278 * "home" setting. Express also supports "home" out of the box,279 * which can be set via `app.set('home', '/blog');`, and defaults280 * to '/'.281 *282 * Redirect Mapping:283 * 284 * To extend the redirect mapping capabilities that Express provides,285 * we may use the `app.redirect()` method:286 * 287 * app.redirect('google', 'http://google.com');288 * 289 * Now in a route we may call:290 *291 * res.redirect('google');292 *293 * We may also map dynamic redirects:294 *295 * app.redirect('comments', function(req, res){296 * return '/post/' + req.params.id + '/comments';297 * });298 *299 * So now we may do the following, and the redirect will dynamically adjust to300 * the context of the request. If we called this route with _GET /post/12_ our301 * redirect _Location_ would be _/post/12/comments_.302 *303 * app.get('/post/:id', function(req, res){miscTj Holowaychukbefore adoption0704f14
line 304why, one step back304 * res.redirect('comments');moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 305–306why, one step back305 * });306 *Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
lines 307–310why, one step back307 * Unless an absolute `url` is given, the app's mount-point308 * will be respected. For example if we redirect to `/posts`,309 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.310 *moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 311–315why, one step back311 * @param {String} url312 * @param {Number} code313 * @api public314 */315Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 316why, one step back316res.redirect = function(url, status){Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
lines 317–318why, one step back317 var app = this.app318 , base = app.set('home') || '/'moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 319–323why, one step back319 , status = status || 302320 , body;321322 // Setup redirect map323 var map = {Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
lines 324–325why, one step back324 back: this.req.header('Referrer', base)325 , home: basemoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 326–331why, one step back326 };327328 // Support custom redirect map329 map.__proto__ = this.app.redirects;330331 // Attempt mapped redirectMerge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 332why, one step back332 var mapped = 'function' == typeof map[url]moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 333–337why, one step back333 ? map[url](this.req, this)334 : map[url];335336 // Perform redirect337 url = mapped || url;Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
lines 338–342why, one step back338339 // Respect mount-point340 if (app.route && !~url.indexOf('://')) {341 url = join(app.route, url);342 } moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 343–353why, one step back343344 // Support text/{plain,html} by default345 if (this.req.accepts('html')) {346 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';347 this.header('Content-Type', 'text/html');348 } else {349 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;350 this.header('Content-Type', 'text/plain');351 }352353 // RespondAdded res.redirect() mount testTj Holowaychukbefore adoption99dcf75
lines 354–356why, one step back354 this.statusCode = status;355 this.header('Location', url);356 this.end(body);moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 357–368why, one step back357};358359/**360 * Assign the view local variable `name` to `val` or return the361 * local previously assigned to `name`.362 *363 * @param {String} name364 * @param {Mixed} val365 * @return {Mixed} val366 * @api public367 */368Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 369why, one step back369res.local = function(name, val){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 370–374why, one step back370 this.locals = this.locals || {};371 return undefined === val372 ? this.locals[name]373 : this.locals[name] = val;374};