response.js
This file
Path
lib/response.js
375 lines · 9.0 KiB · JavaScript
Last changed by
default res.send() string charset to utf8Tj Holowaychukbefore adoptionacbf224
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')) {default res.send() string charset to utf8Tj Holowaychukbefore adoptionacbf224
line 66why, one step back66 this.charset = this.charset || 'utf8';moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 67–71why, one step back67 this.contentType('.html');68 }69 break;70 case 'object':71 if (body instanceof Buffer) {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 72why, one step back72 if (!this.header('Content-Type')) {moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 73–75why, one step back73 this.contentType('.bin');74 }75 } else {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 76why, one step back76 if (!this.header('Content-Type')) {moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 77–79why, one step back77 this.contentType('.json');78 }79 body = JSON.stringify(body);Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 80why, one step back80 if (this.req.query.callback && this.app.set('jsonp callback')) {moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 81–87why, one step back81 this.header('Content-Type', 'text/javascript');82 body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';83 }84 }85 break;86 }87refactored res.send()Tj Holowaychukbefore adoption3661922
line 88why, one step back88 // populate Content-LengthMerge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 89why, one step back89 if (!this.header('Content-Length')) {moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 90–94why, one step back90 this.header('Content-Length', body instanceof Buffer91 ? body.length92 : Buffer.byteLength(body));93 }94refactored res.send()Tj Holowaychukbefore adoption3661922
line 95why, one step back95 // merge headers passedmoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 96–103why, one step back96 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 }103refactored res.send()Tj Holowaychukbefore adoption3661922
line 104why, one step back104 // strip irrelevant headersmoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 105why, one step back105 if (204 === status) {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
lines 106–107why, one step back106 this.removeHeader('Content-Type');107 this.removeHeader('Content-Length');moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 108–109why, one step back108 }109refactored res.send()Tj Holowaychukbefore adoption3661922
lines 110–111why, one step back110 // respond111 this.statusCode = status;moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 112–116why, one step back112 this.end('HEAD' == this.req.method ? undefined : body);113};114115/**116 * Transfer the file at the given `path`. Automatically sets refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
lines 117–118why, one step back117 * the _Content-Type_ response header field. `next()` is called118 * when `path` is a directory, or when an error occurs.moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 119why, one step back119 *refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 120why, one step back120 * Options:moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 121why, one step back121 *refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
lines 122–124why, one step back122 * - `maxAge` defaulting to 0123 * - `root` root directory for relative filenames124 *moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 125why, one step back125 * @param {String} pathres.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
lines 126–127why, one step back126 * @param {Object|Function} options or fn127 * @param {Function} fnmoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 128–130why, one step back128 * @api public129 */130res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
line 131why, one step back131res.sendfile = function(path, options, fn){refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 132why, one step back132 options = options || {};res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
lines 133–139why, one step back133134 // support function as second arg135 if ('function' == typeof options) {136 fn = options;137 options = {};138 }139refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 140why, one step back140 options.path = path;res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
line 141why, one step back141 options.callback = fn;refactoring to use connects static serverTj Holowaychukbefore adoption59a74ec
line 142why, one step back142 send(this.req, this, this.req.next, options);moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 143–145why, one step back143};144145/**replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85
line 146why, one step back146 * Set _Content-Type_ response header passed through `mime.lookup()`.moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 147–163why, one step back147 *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 */163Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 164why, one step back164res.contentType = function(type){replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85
line 165why, one step back165 return this.header('Content-Type', mime.lookup(type));moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 166–175why, one step back166};167168/**169 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.170 *171 * @param {String} filename172 * @return {ServerResponse}173 * @api public174 */175Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 176why, one step back176res.attachment = function(filename){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 177–184why, one step back177 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 res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
line 185why, one step back185 * `filename` as an attachment and optional callback `fn(err)`.moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 186–187why, one step back186 *187 * @param {String} pathres.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
lines 188–189why, one step back188 * @param {String|Function} filename or fn189 * @param {Function} fnmoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 190–193why, one step back190 * @return {Type}191 * @api public192 */193res.download() and res.sendfile() using connect nowTj Holowaychukbefore adoption9b1cc75
lines 194–212why, one step back194res.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 });moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 213–223why, one step back213};214215/**216 * Set or get response header `name` with optional `val`.217 *218 * @param {String} name219 * @param {String} val220 * @return {String}221 * @api public222 */223Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 224why, one step back224res.header = function(name, val){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 225why, one step back225 if (val === undefined) {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
line 226why, one step back226 return this.getHeader(name);moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 227why, one step back227 } else {Merge branch 'progressive-headers'Tj Holowaychukbefore adoption9099c61
lines 228–229why, one step back228 this.setHeader(name, val);229 return val;moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 230–239why, one step back230 }231};232233/**234 * Clear cookie `name`.235 *236 * @param {String} name237 * @api public238 */239Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 240why, one step back240res.clearCookie = function(name){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 241–244why, one step back241 this.cookie(name, '', { expires: new Date(1) });242};243244/**Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
line 245why, one step back245 * Set cookie `name` to `val`, with the given `options`.moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 246why, one step back246 *Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 247–250why, one step back247 * Options:248 *249 * - `maxAge` max-age in milliseconds, converted to `expires`250 *moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 251–255why, one step back251 * Examples:252 *253 * // "Remember Me" for 15 minutes254 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });255 *Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 256–258why, one step back256 * // save as above257 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })258 *moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 259–264why, one step back259 * @param {String} name260 * @param {String} val261 * @param {Options} options262 * @api public263 */264Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 265why, one step back265res.cookie = function(name, val, options){Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 266–267why, one step back266 options = options || {};267 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 268–304why, one step back268 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){miscTj Holowaychukbefore adoption0704f14
line 305why, one step back305 * res.redirect('comments');moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 306–307why, one step back306 * });307 *Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
lines 308–311why, one step back308 * 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 *moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 312–316why, one step back312 * @param {String} url313 * @param {Number} code314 * @api public315 */316Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 317why, one step back317res.redirect = function(url, status){Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
lines 318–319why, one step back318 var app = this.app319 , base = app.set('home') || '/'moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 320–324why, one step back320 , status = status || 302321 , body;322323 // Setup redirect map324 var map = {Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
lines 325–326why, one step back325 back: this.req.header('Referrer', base)326 , home: basemoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 327–332why, one step back327 };328329 // Support custom redirect map330 map.__proto__ = this.app.redirects;331332 // Attempt mapped redirectMerge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
line 333why, one step back333 var mapped = 'function' == typeof map[url]moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 334–338why, one step back334 ? map[url](this.req, this)335 : map[url];336337 // Perform redirect338 url = mapped || url;Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71
lines 339–343why, one step back339340 // Respect mount-point341 if (app.route && !~url.indexOf('://')) {342 url = join(app.route, url);343 } moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 344–354why, one step back344345 // Support text/{plain,html} by default346 if (this.req.accepts('html')) {347 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';348 this.header('Content-Type', 'text/html');349 } else {350 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;351 this.header('Content-Type', 'text/plain');352 }353354 // RespondAdded res.redirect() mount testTj Holowaychukbefore adoption99dcf75
lines 355–357why, one step back355 this.statusCode = status;356 this.header('Location', url);357 this.end(body);moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 358–369why, one step back358};359360/**361 * Assign the view local variable `name` to `val` or return the362 * local previously assigned to `name`.363 *364 * @param {String} name365 * @param {Mixed} val366 * @return {Mixed} val367 * @api public368 */369Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 370why, one step back370res.local = function(name, val){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 371–375why, one step back371 this.locals = this.locals || {};372 return undefined === val373 ? this.locals[name]374 : this.locals[name] = val;375};