request.js
This file
Path
lib/request.js
433 lines · 9.7 KiB · JavaScript
Last changed by
some jshint cleanupJonathan Ongbefore adoption5572897
History of this fileTake it
The walk stopped after 200 commits: lines older than f8a33d1 point at it.
refactorTJ Holowaychukbefore adoptionf8a33d1
lines 1–5why, one step back12/**3 * Module dependencies.4 */5refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 6–7why, one step back6var accepts = require('accepts');7var typeis = require('type-is');refactorTJ Holowaychukbefore adoptionf8a33d1
lines 8–11why, one step back8var http = require('http')9 , utils = require('./utils')10 , fresh = require('fresh')11 , parseRange = require('range-parser')use local copy of parseUrlRoman Shtylmanbefore adoption6a7363e
line 12why, one step back12 , parse = utils.parseUrlrefactorTJ Holowaychukbefore adoptionf8a33d1
lines 13–58why, one step back1314/**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/**refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 59–60why, one step back59 * To do: update docs.60 *refactorTJ Holowaychukbefore adoptionf8a33d1
lines 61–67why, one step back61 * Check if the given `type(s)` is acceptable, returning62 * the best match when true, otherwise `undefined`, in which63 * case you should respond with 406 "Not Acceptable".64 *65 * The `type` value may be a single mime type string66 * such as "application/json", the extension name67 * such as "json", a comma-delimted list such as "json, html, text/plain",Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption752b5f7
line 68why, one step back68 * an argument list such as `"json", "html", "text/plain"`,refactorTJ Holowaychukbefore adoptionf8a33d1
lines 69–94why, one step back69 * or an array `["json", "html", "text/plain"]`. When a list70 * or array is given the _best_ match, if any is returned.71 *72 * Examples:73 *74 * // Accept: text/html75 * req.accepts('html');76 * // => "html"77 *78 * // Accept: text/*, application/json79 * req.accepts('html');80 * // => "html"81 * req.accepts('text/html');82 * // => "text/html"83 * req.accepts('json, text');84 * // => "json"85 * req.accepts('application/json');86 * // => "application/json"87 *88 * // Accept: text/*, application/json89 * req.accepts('image/png');90 * req.accepts('png');91 * // => undefined92 *93 * // Accept: text/*;q=.5, application/json94 * req.accepts(['html', 'json']);Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption752b5f7
line 95why, one step back95 * req.accepts('html', 'json');refactorTJ Holowaychukbefore adoptionf8a33d1
lines 96–103why, one step back96 * req.accepts('html, json');97 * // => "json"98 *99 * @param {String|Array} type(s)100 * @return {String}101 * @api public102 */103refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 104–106why, one step back104req.accepts = function(){105 var accept = accepts(this);106 return accept.types.apply(accept, arguments);refactorTJ Holowaychukbefore adoptionf8a33d1
lines 107–116why, one step back107};108109/**110 * Check if the given `encoding` is accepted.111 *112 * @param {String} encoding113 * @return {Boolean}114 * @api public115 */116refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 117–120why, one step back117req.acceptsEncoding = // backwards compatibility118req.acceptsEncodings = function(){119 var accept = accepts(this);120 return accept.encodings.apply(accept, arguments);refactorTJ Holowaychukbefore adoptionf8a33d1
lines 121–123why, one step back121};122123/**refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 124–125why, one step back124 * To do: update docs.125 *refactorTJ Holowaychukbefore adoptionf8a33d1
lines 126–133why, one step back126 * Check if the given `charset` is acceptable,127 * otherwise you should respond with 406 "Not Acceptable".128 *129 * @param {String} charset130 * @return {Boolean}131 * @api public132 */133refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 134–137why, one step back134req.acceptsCharset = // backwards compatibility135req.acceptsCharsets = function(){136 var accept = accepts(this);137 return accept.charsets.apply(accept, arguments);refactorTJ Holowaychukbefore adoptionf8a33d1
lines 138–140why, one step back138};139140/**refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 141–142why, one step back141 * To do: update docs.142 *refactorTJ Holowaychukbefore adoptionf8a33d1
lines 143–150why, one step back143 * Check if the given `lang` is acceptable,144 * otherwise you should respond with 406 "Not Acceptable".145 *146 * @param {String} lang147 * @return {Boolean}148 * @api public149 */150refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
line 151why, one step back151req.acceptsLanguage = // backwards compatibilitysome jshint cleanupJonathan Ongbefore adoption5572897
line 152why, one step back152req.acceptsLanguages = function(){refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 153–154why, one step back153 var accept = accepts(this);154 return accept.languages.apply(accept, arguments);refactorTJ Holowaychukbefore adoptionf8a33d1
lines 155–191why, one step back155};156157/**158 * Parse Range header field,159 * capping to the given `size`.160 *161 * Unspecified ranges such as "0-" require162 * knowledge of your resource length. In163 * the case of a byte range this is of course164 * the total number of bytes. If the Range165 * header field is not given `null` is returned,166 * `-1` when unsatisfiable, `-2` when syntactically invalid.167 *168 * NOTE: remember that ranges are inclusive, so169 * for example "Range: users=0-3" should respond170 * with 4 users when available, not 3.171 *172 * @param {Number} size173 * @return {Array}174 * @api public175 */176177req.range = function(size){178 var range = this.get('Range');179 if (!range) return;180 return parseRange(size, range);181};182183/**184 * Return the value of param `name` when present or `defaultValue`.185 *186 * - Checks route placeholders, ex: _/user/:id_187 * - Checks body params, ex: id=12, {"id":12}188 * - Checks query string params, ex: ?id=12189 *190 * To utilize request bodies, `req.body`191 * should be an object. This can be done by usingremove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
line 192why, one step back192 * the `bodyParser()` middleware.refactorTJ Holowaychukbefore adoptionf8a33d1
lines 193–235why, one step back193 *194 * @param {String} name195 * @param {Mixed} [defaultValue]196 * @return {String}197 * @api public198 */199200req.param = function(name, defaultValue){201 var params = this.params || {};202 var body = this.body || {};203 var query = this.query || {};204 if (null != params[name] && params.hasOwnProperty(name)) return params[name];205 if (null != body[name]) return body[name];206 if (null != query[name]) return query[name];207 return defaultValue;208};209210/**211 * Check if the incoming request contains the "Content-Type"212 * header field, and it contains the give mime `type`.213 *214 * Examples:215 *216 * // With Content-Type: text/html; charset=utf-8217 * req.is('html');218 * req.is('text/html');219 * req.is('text/*');220 * // => true221 *222 * // When Content-Type is application/json223 * req.is('json');224 * req.is('application/json');225 * req.is('application/*');226 * // => true227 *228 * req.is('html');229 * // => false230 *231 * @param {String} type232 * @return {Boolean}233 * @api public234 */235refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 236–238why, one step back236req.is = function(types){237 if (!Array.isArray(types)) types = [].slice.call(arguments);238 return typeis(this, types);refactorTJ Holowaychukbefore adoptionf8a33d1
lines 239–254why, one step back239};240241/**242 * Return the protocol string "http" or "https"243 * when requested with TLS. When the "trust proxy"244 * setting is enabled the "X-Forwarded-Proto" header245 * field will be trusted. If you're running behind246 * a reverse proxy that supplies https for you this247 * may be enabled.248 *249 * @return {String}250 * @api public251 */252253req.__defineGetter__('protocol', function(){254 var trustProxy = this.app.get('trust proxy');add support for multiple X-Forwarded-Proto values. Closes #1646TJ Holowaychukbefore adoption8ab4408
lines 255–258why, one step back255 if (this.connection.encrypted) return 'https';256 if (!trustProxy) return 'http';257 var proto = this.get('X-Forwarded-Proto') || 'http';258 return proto.split(/\s*,\s*/)[0];refactorTJ Holowaychukbefore adoptionf8a33d1
lines 259–353why, one step back259});260261/**262 * Short-hand for:263 *264 * req.protocol == 'https'265 *266 * @return {Boolean}267 * @api public268 */269270req.__defineGetter__('secure', function(){271 return 'https' == this.protocol;272});273274/**275 * Return the remote address, or when276 * "trust proxy" is `true` return277 * the upstream addr.278 *279 * @return {String}280 * @api public281 */282283req.__defineGetter__('ip', function(){284 return this.ips[0] || this.connection.remoteAddress;285});286287/**288 * When "trust proxy" is `true`, parse289 * the "X-Forwarded-For" ip address list.290 *291 * For example if the value were "client, proxy1, proxy2"292 * you would receive the array `["client", "proxy1", "proxy2"]`293 * where "proxy2" is the furthest down-stream.294 *295 * @return {Array}296 * @api public297 */298299req.__defineGetter__('ips', function(){300 var trustProxy = this.app.get('trust proxy');301 var val = this.get('X-Forwarded-For');302 return trustProxy && val303 ? val.split(/ *, */)304 : [];305});306307/**308 * Return basic auth credentials.309 *310 * Examples:311 *312 * // http://tobi:hello@example.com313 * req.auth314 * // => { username: 'tobi', password: 'hello' }315 *316 * @return {Object} or undefined317 * @api public318 */319320req.__defineGetter__('auth', function(){321 // missing322 var auth = this.get('Authorization');323 if (!auth) return;324325 // malformed326 var parts = auth.split(' ');327 if ('basic' != parts[0].toLowerCase()) return;328 if (!parts[1]) return;329 auth = parts[1];330331 // credentials332 auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/);333 if (!auth) return;334 return { username: auth[1], password: auth[2] };335});336337/**338 * Return subdomains as an array.339 *340 * Subdomains are the dot-separated parts of the host before the main domain of341 * the app. By default, the domain of the app is assumed to be the last two342 * parts of the host. This can be changed by setting "subdomain offset".343 *344 * For example, if the domain is "tobi.ferrets.example.com":345 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.346 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.347 *348 * @return {Array}349 * @api public350 */351352req.__defineGetter__('subdomains', function(){353 var offset = this.app.get('subdomain offset');fix `req.subdomains` when no Host is presentTJ Holowaychukbefore adoption8559c0e
line 354why, one step back354 return (this.host || '')refactorTJ Holowaychukbefore adoptionf8a33d1
lines 355–381why, one step back355 .split('.')356 .reverse()357 .slice(offset);358});359360/**361 * Short-hand for `url.parse(req.url).pathname`.362 *363 * @return {String}364 * @api public365 */366367req.__defineGetter__('path', function(){368 return parse(this).pathname;369});370371/**372 * Parse the "Host" header field hostname.373 *374 * @return {String}375 * @api public376 */377378req.__defineGetter__('host', function(){379 var trustProxy = this.app.get('trust proxy');380 var host = trustProxy && this.get('X-Forwarded-Host');381 host = host || this.get('Host');fix `req.host` when no Host is present, return undefinedTJ Holowaychukbefore adoption06ead58
line 382why, one step back382 if (!host) return;refactorTJ Holowaychukbefore adoptionf8a33d1
lines 383–433why, one step back383 return host.split(':')[0];384});385386/**387 * Check if the request is fresh, aka388 * Last-Modified and/or the ETag389 * still match.390 *391 * @return {Boolean}392 * @api public393 */394395req.__defineGetter__('fresh', function(){396 var method = this.method;397 var s = this.res.statusCode;398399 // GET or HEAD for weak freshness validation only400 if ('GET' != method && 'HEAD' != method) return false;401402 // 2xx or 304 as per rfc2616 14.26403 if ((s >= 200 && s < 300) || 304 == s) {404 return fresh(this.headers, this.res._headers);405 }406407 return false;408});409410/**411 * Check if the request is stale, aka412 * "Last-Modified" and / or the "ETag" for the413 * resource has changed.414 *415 * @return {Boolean}416 * @api public417 */418419req.__defineGetter__('stale', function(){420 return !this.fresh;421});422423/**424 * Check if the request was an _XMLHttpRequest_.425 *426 * @return {Boolean}427 * @api public428 */429430req.__defineGetter__('xhr', function(){431 var val = this.get('X-Requested-With') || '';432 return 'xmlhttprequest' == val.toLowerCase();433});