request.js
This file
Path
lib/request.js
535 lines · 11.7 KiB · JavaScript
Last changed by
Merge branch '3.5.x' into 3.xDouglas Christopher Wilsonbefore adoption66b38b5
History of this fileTake it
The walk stopped after 200 commits: lines older than 6654b71 point at it.
Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 1–65why, one step back12/**3 * Module dependencies.4 */56var http = require('http')7 , utils = require('./utils')8 , connect = require('connect')9 , fresh = require('fresh')10 , parseRange = require('range-parser')11 , parse = connect.utils.parseUrl12 , mime = connect.mime;1314/**15 * Request prototype.16 */1718var req = exports = module.exports = {19 __proto__: http.IncomingMessage.prototype20};2122/**23 * Return request header.24 *25 * The `Referrer` header field is special-cased,26 * both `Referrer` and `Referer` are interchangeable.27 *28 * Examples:29 *30 * req.get('Content-Type');31 * // => "text/plain"32 *33 * req.get('content-type');34 * // => "text/plain"35 *36 * req.get('Something');37 * // => undefined38 *39 * Aliased as `req.header()`.40 *41 * @param {String} name42 * @return {String}43 * @api public44 */4546req.get =47req.header = function(name){48 switch (name = name.toLowerCase()) {49 case 'referer':50 case 'referrer':51 return this.headers.referrer52 || this.headers.referer;53 default:54 return this.headers[name];55 }56};5758/**59 * Check if the given `type(s)` is acceptable, returning60 * the best match when true, otherwise `undefined`, in which61 * case you should respond with 406 "Not Acceptable".62 *63 * The `type` value may be a single mime type string64 * such as "application/json", the extension name65 * such as "json", a comma-delimted list such as "json, html, text/plain",Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption752b5f7
line 66why, one step back66 * an argument list such as `"json", "html", "text/plain"`,Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 67–92why, one step back67 * or an array `["json", "html", "text/plain"]`. When a list68 * or array is given the _best_ match, if any is returned.69 *70 * Examples:71 *72 * // Accept: text/html73 * req.accepts('html');74 * // => "html"75 *76 * // Accept: text/*, application/json77 * req.accepts('html');78 * // => "html"79 * req.accepts('text/html');80 * // => "text/html"81 * req.accepts('json, text');82 * // => "json"83 * req.accepts('application/json');84 * // => "application/json"85 *86 * // Accept: text/*, application/json87 * req.accepts('image/png');88 * req.accepts('png');89 * // => undefined90 *91 * // Accept: text/*;q=.5, application/json92 * req.accepts(['html', 'json']);Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption752b5f7
line 93why, one step back93 * req.accepts('html', 'json');Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 94–102why, one step back94 * req.accepts('html, json');95 * // => "json"96 *97 * @param {String|Array} type(s)98 * @return {String}99 * @api public100 */101102req.accepts = function(type){Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption752b5f7
lines 103–104why, one step back103 var args = arguments.length > 1 ? [].slice.apply(arguments) : type;104 return utils.accepts(args, this.get('Accept'));Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 105–107why, one step back105};106107/**add req.acceptsEncoding(name)TJ Holowaychukbefore adoption2e53cb7
lines 108–115why, one step back108 * Check if the given `encoding` is accepted.109 *110 * @param {String} encoding111 * @return {Boolean}112 * @api public113 */114115req.acceptsEncoding = function(encoding){return actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b
line 116why, one step back116 return !! ~this.acceptedEncodings.indexOf(encoding);add req.acceptsEncoding(name)TJ Holowaychukbefore adoption2e53cb7
lines 117–119why, one step back117};118119/**Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 120–130why, one step back120 * Check if the given `charset` is acceptable,121 * otherwise you should respond with 406 "Not Acceptable".122 *123 * @param {String} charset124 * @return {Boolean}125 * @api public126 */127128req.acceptsCharset = function(charset){129 var accepted = this.acceptedCharsets;130 return accepted.lengthreturn actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b
line 131why, one step back131 ? !! ~accepted.indexOf(charset)Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 132–146why, one step back132 : true;133};134135/**136 * Check if the given `lang` is acceptable,137 * otherwise you should respond with 406 "Not Acceptable".138 *139 * @param {String} lang140 * @return {Boolean}141 * @api public142 */143144req.acceptsLanguage = function(lang){145 var accepted = this.acceptedLanguages;146 return accepted.lengthreturn actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b
line 147why, one step back147 ? !! ~accepted.indexOf(lang)Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 148–177why, one step back148 : true;149};150151/**152 * Parse Range header field,153 * capping to the given `size`.154 *155 * Unspecified ranges such as "0-" require156 * knowledge of your resource length. In157 * the case of a byte range this is of course158 * the total number of bytes. If the Range159 * header field is not given `null` is returned,160 * `-1` when unsatisfiable, `-2` when syntactically invalid.161 *162 * NOTE: remember that ranges are inclusive, so163 * for example "Range: users=0-3" should respond164 * with 4 users when available, not 3.165 *166 * @param {Number} size167 * @return {Array}168 * @api public169 */170171req.range = function(size){172 var range = this.get('Range');173 if (!range) return;174 return parseRange(size, range);175};176177/**add req.acceptedEncodingsTJ Holowaychukbefore adoption3b1597d
lines 178–195why, one step back178 * Return an array of encodings.179 *180 * Examples:181 *182 * ['gzip', 'deflate']183 *184 * @return {Array}185 * @api public186 */187188req.__defineGetter__('acceptedEncodings', function(){189 var accept = this.get('Accept-Encoding');190 return accept191 ? accept.trim().split(/ *, */)192 : [];193});194195/**Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 196–237why, one step back196 * Return an array of Accepted media types197 * ordered from highest quality to lowest.198 *199 * Examples:200 *201 * [ { value: 'application/json',202 * quality: 1,203 * type: 'application',204 * subtype: 'json' },205 * { value: 'text/html',206 * quality: 0.5,207 * type: 'text',208 * subtype: 'html' } ]209 *210 * @return {Array}211 * @api public212 */213214req.__defineGetter__('accepted', function(){215 var accept = this.get('Accept');216 return accept217 ? utils.parseAccept(accept)218 : [];219});220221/**222 * Return an array of Accepted languages223 * ordered from highest quality to lowest.224 *225 * Examples:226 *227 * Accept-Language: en;q=.5, en-us228 * ['en-us', 'en']229 *230 * @return {Array}231 * @api public232 */233234req.__defineGetter__('acceptedLanguages', function(){235 var accept = this.get('Accept-Language');236 return accept237 ? utilsadd support for custom Accept parametersPavel Brylovbefore adoption9e684d4
line 238why, one step back238 .parseParams(accept)Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 239–261why, one step back239 .map(function(obj){240 return obj.value;241 })242 : [];243});244245/**246 * Return an array of Accepted charsets247 * ordered from highest quality to lowest.248 *249 * Examples:250 *251 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8252 * ['unicode-1-1', 'iso-8859-5']253 *254 * @return {Array}255 * @api public256 */257258req.__defineGetter__('acceptedCharsets', function(){259 var accept = this.get('Accept-Charset');260 return accept261 ? utilsadd support for custom Accept parametersPavel Brylovbefore adoption9e684d4
line 262why, one step back262 .parseParams(accept)Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 263–280why, one step back263 .map(function(obj){264 return obj.value;265 })266 : [];267});268269/**270 * Return the value of param `name` when present or `defaultValue`.271 *272 * - Checks route placeholders, ex: _/user/:id_273 * - Checks body params, ex: id=12, {"id":12}274 * - Checks query string params, ex: ?id=12275 *276 * To utilize request bodies, `req.body`277 * should be an object. This can be done by using278 * the `connect.bodyParser()` middleware.279 *280 * @param {String} namedocsTJ Holowaychukbefore adoptiond1bafa0
line 281why, one step back281 * @param {Mixed} [defaultValue]Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 282–350why, one step back282 * @return {String}283 * @api public284 */285286req.param = function(name, defaultValue){287 var params = this.params || {};288 var body = this.body || {};289 var query = this.query || {};290 if (null != params[name] && params.hasOwnProperty(name)) return params[name];291 if (null != body[name]) return body[name];292 if (null != query[name]) return query[name];293 return defaultValue;294};295296/**297 * Check if the incoming request contains the "Content-Type"298 * header field, and it contains the give mime `type`.299 *300 * Examples:301 *302 * // With Content-Type: text/html; charset=utf-8303 * req.is('html');304 * req.is('text/html');305 * req.is('text/*');306 * // => true307 *308 * // When Content-Type is application/json309 * req.is('json');310 * req.is('application/json');311 * req.is('application/*');312 * // => true313 *314 * req.is('html');315 * // => false316 *317 * @param {String} type318 * @return {Boolean}319 * @api public320 */321322req.is = function(type){323 var ct = this.get('Content-Type');324 if (!ct) return false;325 ct = ct.split(';')[0];326 if (!~type.indexOf('/')) type = mime.lookup(type);327 if (~type.indexOf('*')) {328 type = type.split('/');329 ct = ct.split('/');330 if ('*' == type[0] && type[1] == ct[1]) return true;331 if ('*' == type[1] && type[0] == ct[0]) return true;332 return false;333 }334 return !! ~ct.indexOf(type);335};336337/**338 * Return the protocol string "http" or "https"339 * when requested with TLS. When the "trust proxy"340 * setting is enabled the "X-Forwarded-Proto" header341 * field will be trusted. If you're running behind342 * a reverse proxy that supplies https for you this343 * may be enabled.344 *345 * @return {String}346 * @api public347 */348349req.__defineGetter__('protocol', function(){350 var trustProxy = this.app.get('trust proxy');add support for multiple X-Forwarded-Proto values. Closes #1646TJ Holowaychukbefore adoption8ab4408
lines 351–354why, one step back351 if (this.connection.encrypted) return 'https';352 if (!trustProxy) return 'http';353 var proto = this.get('X-Forwarded-Proto') || 'http';354 return proto.split(/\s*,\s*/)[0];Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 355–449why, one step back355});356357/**358 * Short-hand for:359 *360 * req.protocol == 'https'361 *362 * @return {Boolean}363 * @api public364 */365366req.__defineGetter__('secure', function(){367 return 'https' == this.protocol;368});369370/**371 * Return the remote address, or when372 * "trust proxy" is `true` return373 * the upstream addr.374 *375 * @return {String}376 * @api public377 */378379req.__defineGetter__('ip', function(){380 return this.ips[0] || this.connection.remoteAddress;381});382383/**384 * When "trust proxy" is `true`, parse385 * the "X-Forwarded-For" ip address list.386 *387 * For example if the value were "client, proxy1, proxy2"388 * you would receive the array `["client", "proxy1", "proxy2"]`389 * where "proxy2" is the furthest down-stream.390 *391 * @return {Array}392 * @api public393 */394395req.__defineGetter__('ips', function(){396 var trustProxy = this.app.get('trust proxy');397 var val = this.get('X-Forwarded-For');398 return trustProxy && val399 ? val.split(/ *, */)400 : [];401});402403/**404 * Return basic auth credentials.405 *406 * Examples:407 *408 * // http://tobi:hello@example.com409 * req.auth410 * // => { username: 'tobi', password: 'hello' }411 *412 * @return {Object} or undefined413 * @api public414 */415416req.__defineGetter__('auth', function(){417 // missing418 var auth = this.get('Authorization');419 if (!auth) return;420421 // malformed422 var parts = auth.split(' ');423 if ('basic' != parts[0].toLowerCase()) return;424 if (!parts[1]) return;425 auth = parts[1];426427 // credentials428 auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/);429 if (!auth) return;430 return { username: auth[1], password: auth[2] };431});432433/**434 * Return subdomains as an array.435 *436 * Subdomains are the dot-separated parts of the host before the main domain of437 * the app. By default, the domain of the app is assumed to be the last two438 * parts of the host. This can be changed by setting "subdomain offset".439 *440 * For example, if the domain is "tobi.ferrets.example.com":441 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.442 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.443 *444 * @return {Array}445 * @api public446 */447448req.__defineGetter__('subdomains', function(){449 var offset = this.app.get('subdomain offset');fix `req.subdomains` when no Host is presentTJ Holowaychukbefore adoption8559c0e
line 450why, one step back450 return (this.host || '')Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 451–475why, one step back451 .split('.')452 .reverse()453 .slice(offset);454});455456/**457 * Short-hand for `url.parse(req.url).pathname`.458 *459 * @return {String}460 * @api public461 */462463req.__defineGetter__('path', function(){464 return parse(this).pathname;465});466467/**468 * Parse the "Host" header field hostname.469 *470 * @return {String}471 * @api public472 */473474req.__defineGetter__('host', function(){475 var trustProxy = this.app.get('trust proxy');refactor req.hostTJ Holowaychukbefore adoption4a1fa58
lines 476–477why, one step back476 var host = trustProxy && this.get('X-Forwarded-Host');477 host = host || this.get('Host');fix `req.host` when no Host is present, return undefinedTJ Holowaychukbefore adoption06ead58
line 478why, one step back478 if (!host) return;Merge branch '3.5.x' into 3.xDouglas Christopher Wilsonbefore adoption66b38b5
lines 479–485why, one step back479 var offset = host[0] === '['480 ? host.indexOf(']') + 1481 : 0;482 var index = host.indexOf(':', offset);483 return ~index484 ? host.substring(0, index)485 : host;Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
lines 486–535why, one step back486});487488/**489 * Check if the request is fresh, aka490 * Last-Modified and/or the ETag491 * still match.492 *493 * @return {Boolean}494 * @api public495 */496497req.__defineGetter__('fresh', function(){498 var method = this.method;499 var s = this.res.statusCode;500501 // GET or HEAD for weak freshness validation only502 if ('GET' != method && 'HEAD' != method) return false;503504 // 2xx or 304 as per rfc2616 14.26505 if ((s >= 200 && s < 300) || 304 == s) {506 return fresh(this.headers, this.res._headers);507 }508509 return false;510});511512/**513 * Check if the request is stale, aka514 * "Last-Modified" and / or the "ETag" for the515 * resource has changed.516 *517 * @return {Boolean}518 * @api public519 */520521req.__defineGetter__('stale', function(){522 return !this.fresh;523});524525/**526 * Check if the request was an _XMLHttpRequest_.527 *528 * @return {Boolean}529 * @api public530 */531532req.__defineGetter__('xhr', function(){533 var val = this.get('X-Requested-With') || '';534 return 'xmlhttprequest' == val.toLowerCase();535});