request.js
This file
Path
lib/request.js
549 lines · 12.0 KiB · JavaScript
Last changed by
add deprecation message to req.authDouglas Christopher Wilsonbefore adoptionf381f2d
History of this fileTake it
The walk stopped after 200 commits: lines older than 13d3efe point at it.
update freshTJ Holowaychukbefore adoption13d3efe
lines 1–5why, one step back12/**3 * Module dependencies.4 */5add deprecation message to req.authDouglas Christopher Wilsonbefore adoptionf381f2d
lines 6–7why, one step back6var auth = require('basic-auth');7var deprecate = require('depd')('express');update freshTJ Holowaychukbefore adoption13d3efe
lines 8–12why, one step back8var http = require('http')9 , utils = require('./utils')10 , connect = require('connect')11 , fresh = require('fresh')12 , parseRange = require('range-parser')update connect to 2.16.1Douglas Christopher Wilsonbefore adoption65f13c3
line 13why, one step back13 , parse = require('parseurl')improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
line 14why, one step back14 , proxyaddr = require('proxy-addr')update freshTJ Holowaychukbefore adoption13d3efe
lines 15–68why, one step back15 , mime = connect.mime;1617/**18 * Request prototype.19 */2021var req = exports = module.exports = {22 __proto__: http.IncomingMessage.prototype23};2425/**26 * Return request header.27 *28 * The `Referrer` header field is special-cased,29 * both `Referrer` and `Referer` are interchangeable.30 *31 * Examples:32 *33 * req.get('Content-Type');34 * // => "text/plain"35 *36 * req.get('content-type');37 * // => "text/plain"38 *39 * req.get('Something');40 * // => undefined41 *42 * Aliased as `req.header()`.43 *44 * @param {String} name45 * @return {String}46 * @api public47 */4849req.get =50req.header = function(name){51 switch (name = name.toLowerCase()) {52 case 'referer':53 case 'referrer':54 return this.headers.referrer55 || this.headers.referer;56 default:57 return this.headers[name];58 }59};6061/**62 * Check if the given `type(s)` is acceptable, returning63 * the best match when true, otherwise `undefined`, in which64 * case you should respond with 406 "Not Acceptable".65 *66 * The `type` value may be a single mime type string67 * such as "application/json", the extension name68 * such as "json", a comma-delimted list such as "json, html, text/plain",Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption752b5f7
line 69why, one step back69 * an argument list such as `"json", "html", "text/plain"`,update freshTJ Holowaychukbefore adoption13d3efe
lines 70–95why, one step back70 * or an array `["json", "html", "text/plain"]`. When a list71 * or array is given the _best_ match, if any is returned.72 *73 * Examples:74 *75 * // Accept: text/html76 * req.accepts('html');77 * // => "html"78 *79 * // Accept: text/*, application/json80 * req.accepts('html');81 * // => "html"82 * req.accepts('text/html');83 * // => "text/html"84 * req.accepts('json, text');85 * // => "json"86 * req.accepts('application/json');87 * // => "application/json"88 *89 * // Accept: text/*, application/json90 * req.accepts('image/png');91 * req.accepts('png');92 * // => undefined93 *94 * // Accept: text/*;q=.5, application/json95 * req.accepts(['html', 'json']);Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption752b5f7
line 96why, one step back96 * req.accepts('html', 'json');update freshTJ Holowaychukbefore adoption13d3efe
lines 97–105why, one step back97 * req.accepts('html, json');98 * // => "json"99 *100 * @param {String|Array} type(s)101 * @return {String}102 * @api public103 */104105req.accepts = function(type){Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption752b5f7
lines 106–107why, one step back106 var args = arguments.length > 1 ? [].slice.apply(arguments) : type;107 return utils.accepts(args, this.get('Accept'));update freshTJ Holowaychukbefore adoption13d3efe
lines 108–342why, one step back108};109110/**111 * Check if the given `encoding` is accepted.112 *113 * @param {String} encoding114 * @return {Boolean}115 * @api public116 */117118req.acceptsEncoding = function(encoding){119 return !! ~this.acceptedEncodings.indexOf(encoding);120};121122/**123 * Check if the given `charset` is acceptable,124 * otherwise you should respond with 406 "Not Acceptable".125 *126 * @param {String} charset127 * @return {Boolean}128 * @api public129 */130131req.acceptsCharset = function(charset){132 var accepted = this.acceptedCharsets;133 return accepted.length134 ? !! ~accepted.indexOf(charset)135 : true;136};137138/**139 * Check if the given `lang` is acceptable,140 * otherwise you should respond with 406 "Not Acceptable".141 *142 * @param {String} lang143 * @return {Boolean}144 * @api public145 */146147req.acceptsLanguage = function(lang){148 var accepted = this.acceptedLanguages;149 return accepted.length150 ? !! ~accepted.indexOf(lang)151 : true;152};153154/**155 * Parse Range header field,156 * capping to the given `size`.157 *158 * Unspecified ranges such as "0-" require159 * knowledge of your resource length. In160 * the case of a byte range this is of course161 * the total number of bytes. If the Range162 * header field is not given `null` is returned,163 * `-1` when unsatisfiable, `-2` when syntactically invalid.164 *165 * NOTE: remember that ranges are inclusive, so166 * for example "Range: users=0-3" should respond167 * with 4 users when available, not 3.168 *169 * @param {Number} size170 * @return {Array}171 * @api public172 */173174req.range = function(size){175 var range = this.get('Range');176 if (!range) return;177 return parseRange(size, range);178};179180/**181 * Return an array of encodings.182 *183 * Examples:184 *185 * ['gzip', 'deflate']186 *187 * @return {Array}188 * @api public189 */190191req.__defineGetter__('acceptedEncodings', function(){192 var accept = this.get('Accept-Encoding');193 return accept194 ? accept.trim().split(/ *, */)195 : [];196});197198/**199 * Return an array of Accepted media types200 * ordered from highest quality to lowest.201 *202 * Examples:203 *204 * [ { value: 'application/json',205 * quality: 1,206 * type: 'application',207 * subtype: 'json' },208 * { value: 'text/html',209 * quality: 0.5,210 * type: 'text',211 * subtype: 'html' } ]212 *213 * @return {Array}214 * @api public215 */216217req.__defineGetter__('accepted', function(){218 var accept = this.get('Accept');219 return accept220 ? utils.parseAccept(accept)221 : [];222});223224/**225 * Return an array of Accepted languages226 * ordered from highest quality to lowest.227 *228 * Examples:229 *230 * Accept-Language: en;q=.5, en-us231 * ['en-us', 'en']232 *233 * @return {Array}234 * @api public235 */236237req.__defineGetter__('acceptedLanguages', function(){238 var accept = this.get('Accept-Language');239 return accept240 ? utils241 .parseParams(accept)242 .map(function(obj){243 return obj.value;244 })245 : [];246});247248/**249 * Return an array of Accepted charsets250 * ordered from highest quality to lowest.251 *252 * Examples:253 *254 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8255 * ['unicode-1-1', 'iso-8859-5']256 *257 * @return {Array}258 * @api public259 */260261req.__defineGetter__('acceptedCharsets', function(){262 var accept = this.get('Accept-Charset');263 return accept264 ? utils265 .parseParams(accept)266 .map(function(obj){267 return obj.value;268 })269 : [];270});271272/**273 * Return the value of param `name` when present or `defaultValue`.274 *275 * - Checks route placeholders, ex: _/user/:id_276 * - Checks body params, ex: id=12, {"id":12}277 * - Checks query string params, ex: ?id=12278 *279 * To utilize request bodies, `req.body`280 * should be an object. This can be done by using281 * the `connect.bodyParser()` middleware.282 *283 * @param {String} name284 * @param {Mixed} [defaultValue]285 * @return {String}286 * @api public287 */288289req.param = function(name, defaultValue){290 var params = this.params || {};291 var body = this.body || {};292 var query = this.query || {};293 if (null != params[name] && params.hasOwnProperty(name)) return params[name];294 if (null != body[name]) return body[name];295 if (null != query[name]) return query[name];296 return defaultValue;297};298299/**300 * Check if the incoming request contains the "Content-Type"301 * header field, and it contains the give mime `type`.302 *303 * Examples:304 *305 * // With Content-Type: text/html; charset=utf-8306 * req.is('html');307 * req.is('text/html');308 * req.is('text/*');309 * // => true310 *311 * // When Content-Type is application/json312 * req.is('json');313 * req.is('application/json');314 * req.is('application/*');315 * // => true316 *317 * req.is('html');318 * // => false319 *320 * @param {String} type321 * @return {Boolean}322 * @api public323 */324325req.is = function(type){326 var ct = this.get('Content-Type');327 if (!ct) return false;328 ct = ct.split(';')[0];329 if (!~type.indexOf('/')) type = mime.lookup(type);330 if (~type.indexOf('*')) {331 type = type.split('/');332 ct = ct.split('/');333 if ('*' == type[0] && type[1] == ct[1]) return true;334 if ('*' == type[1] && type[0] == ct[0]) return true;335 return false;336 }337 return !! ~ct.indexOf(type);338};339340/**341 * Return the protocol string "http" or "https"342 * when requested with TLS. When the "trust proxy"improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 343–346why, one step back343 * setting trusts the socket address, the344 * "X-Forwarded-Proto" header field will be trusted.345 * If you're running behind a reverse proxy that346 * supplies https for you this may be enabled.update freshTJ Holowaychukbefore adoption13d3efe
lines 347–352why, one step back347 *348 * @return {String}349 * @api public350 */351352req.__defineGetter__('protocol', function(){improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 353–362why, one step back353 var trust = this.app.get('trust proxy fn');354355 if (!trust(this.connection.remoteAddress)) {356 return this.connection.encrypted357 ? 'https'358 : 'http';359 }360361 // Note: X-Forwarded-Proto is normally only ever a362 // single value, but this is to be safe.update freshTJ Holowaychukbefore adoption13d3efe
lines 363–380why, one step back363 var proto = this.get('X-Forwarded-Proto') || 'http';364 return proto.split(/\s*,\s*/)[0];365});366367/**368 * Short-hand for:369 *370 * req.protocol == 'https'371 *372 * @return {Boolean}373 * @api public374 */375376req.__defineGetter__('secure', function(){377 return 'https' == this.protocol;378});379380/**improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
line 381why, one step back381 * Return the remote address from the trusted proxy.update freshTJ Holowaychukbefore adoption13d3efe
line 382why, one step back382 *improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 383–385why, one step back383 * The is the remote address on the socket unless384 * "trust proxy" is set.385 *update freshTJ Holowaychukbefore adoption13d3efe
lines 386–390why, one step back386 * @return {String}387 * @api public388 */389390req.__defineGetter__('ip', function(){improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 391–392why, one step back391 var trust = this.app.get('trust proxy fn');392 return proxyaddr(this, trust);update freshTJ Holowaychukbefore adoption13d3efe
lines 393–395why, one step back393});394395/**improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
line 396why, one step back396 * When "trust proxy" is set, trusted proxy addresses + client.update freshTJ Holowaychukbefore adoption13d3efe
lines 397–399why, one step back397 *398 * For example if the value were "client, proxy1, proxy2"399 * you would receive the array `["client", "proxy1", "proxy2"]`improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 400–401why, one step back400 * where "proxy2" is the furthest down-stream and "proxy1" and401 * "proxy2" were trusted.update freshTJ Holowaychukbefore adoption13d3efe
lines 402–407why, one step back402 *403 * @return {Array}404 * @api public405 */406407req.__defineGetter__('ips', function(){improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 408–410why, one step back408 var trust = this.app.get('trust proxy fn');409 var addrs = proxyaddr.all(this, trust);410 return addrs.slice(1).reverse();update freshTJ Holowaychukbefore adoption13d3efe
lines 411–426why, one step back411});412413/**414 * Return basic auth credentials.415 *416 * Examples:417 *418 * // http://tobi:hello@example.com419 * req.auth420 * // => { username: 'tobi', password: 'hello' }421 *422 * @return {Object} or undefined423 * @api public424 */425426req.__defineGetter__('auth', function(){add deprecation message to req.authDouglas Christopher Wilsonbefore adoptionf381f2d
line 427why, one step back427 deprecate('req.auth: Use basic-auth module directly');update freshTJ Holowaychukbefore adoption13d3efe
lines 428–429why, one step back428429 // credentialsadd deprecation message to req.authDouglas Christopher Wilsonbefore adoptionf381f2d
lines 430–433why, one step back430 var creds = auth(this);431 if (!creds) return;432433 return { username: creds.name, password: creds.pass };update freshTJ Holowaychukbefore adoption13d3efe
lines 434–472why, one step back434});435436/**437 * Return subdomains as an array.438 *439 * Subdomains are the dot-separated parts of the host before the main domain of440 * the app. By default, the domain of the app is assumed to be the last two441 * parts of the host. This can be changed by setting "subdomain offset".442 *443 * For example, if the domain is "tobi.ferrets.example.com":444 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.445 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.446 *447 * @return {Array}448 * @api public449 */450451req.__defineGetter__('subdomains', function(){452 var offset = this.app.get('subdomain offset');453 return (this.host || '')454 .split('.')455 .reverse()456 .slice(offset);457});458459/**460 * Short-hand for `url.parse(req.url).pathname`.461 *462 * @return {String}463 * @api public464 */465466req.__defineGetter__('path', function(){467 return parse(this).pathname;468});469470/**471 * Parse the "Host" header field hostname.472 *improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 473–476why, one step back473 * When the "trust proxy" setting trusts the socket474 * address, the "X-Forwarded-Host" header field will475 * be trusted.476 *update freshTJ Holowaychukbefore adoption13d3efe
lines 477–481why, one step back477 * @return {String}478 * @api public479 */480481req.__defineGetter__('host', function(){improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 482–488why, one step back482 var trust = this.app.get('trust proxy fn');483 var host = this.get('X-Forwarded-Host');484485 if (!host || !trust(this.connection.remoteAddress)) {486 host = this.get('Host');487 }488update freshTJ Holowaychukbefore adoption13d3efe
line 489why, one step back489 if (!host) return;improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 490–491why, one step back490491 // IPv6 literal supportMerge branch '3.5.x' into 3.xDouglas Christopher Wilsonbefore adoption66b38b5
lines 492–495why, one step back492 var offset = host[0] === '['493 ? host.indexOf(']') + 1494 : 0;495 var index = host.indexOf(':', offset);improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
line 496why, one step back496Merge branch '3.5.x' into 3.xDouglas Christopher Wilsonbefore adoption66b38b5
lines 497–499why, one step back497 return ~index498 ? host.substring(0, index)499 : host;update freshTJ Holowaychukbefore adoption13d3efe
lines 500–549why, one step back500});501502/**503 * Check if the request is fresh, aka504 * Last-Modified and/or the ETag505 * still match.506 *507 * @return {Boolean}508 * @api public509 */510511req.__defineGetter__('fresh', function(){512 var method = this.method;513 var s = this.res.statusCode;514515 // GET or HEAD for weak freshness validation only516 if ('GET' != method && 'HEAD' != method) return false;517518 // 2xx or 304 as per rfc2616 14.26519 if ((s >= 200 && s < 300) || 304 == s) {520 return fresh(this.headers, this.res._headers);521 }522523 return false;524});525526/**527 * Check if the request is stale, aka528 * "Last-Modified" and / or the "ETag" for the529 * resource has changed.530 *531 * @return {Boolean}532 * @api public533 */534535req.__defineGetter__('stale', function(){536 return !this.fresh;537});538539/**540 * Check if the request was an _XMLHttpRequest_.541 *542 * @return {Boolean}543 * @api public544 */545546req.__defineGetter__('xhr', function(){547 var val = this.get('X-Requested-With') || '';548 return 'xmlhttprequest' == val.toLowerCase();549});