request.js
This file
Path
lib/request.js
552 lines · 12.1 KiB · JavaScript
Last changed by
Adjust wording on deprecation messagesDouglas Christopher Wilsonbefore adoptionf724730
History of this fileTake it
The walk stopped after 200 commits: lines older than 89e7264 point at it.
pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
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');pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
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')pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
lines 15–342why, 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",69 * an argument list such as `"json", "html", "text/plain"`,70 * 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']);96 * req.accepts('html', 'json');97 * req.accepts('html, json');98 * // => "json"99 *100 * @param {String|Array} type(s)101 * @return {String}102 * @api public103 */104105req.accepts = function(type){106 var args = arguments.length > 1 ? [].slice.apply(arguments) : type;107 return utils.accepts(args, this.get('Accept'));108};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
line 343why, one step back343 * setting trusts the socket address, theFix req.protocol for proxy-direct connectionsAshley Strebbefore adoptiona28b7a8
lines 344–346why, one step back344 * "X-Forwarded-Proto" header field will be trusted345 * and used if present.346 *improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 347–348why, one step back347 * If you're running behind a reverse proxy that348 * supplies https for you this may be enabled.pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
lines 349–354why, one step back349 *350 * @return {String}351 * @api public352 */353354req.__defineGetter__('protocol', function(){Fix req.protocol for proxy-direct connectionsAshley Strebbefore adoptiona28b7a8
lines 355–357why, one step back355 var proto = this.connection.encrypted356 ? 'https'357 : 'http';improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 358–360why, one step back358 var trust = this.app.get('trust proxy fn');359360 if (!trust(this.connection.remoteAddress)) {Fix req.protocol for proxy-direct connectionsAshley Strebbefore adoptiona28b7a8
line 361why, one step back361 return proto;improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 362–365why, one step back362 }363364 // Note: X-Forwarded-Proto is normally only ever a365 // single value, but this is to be safe.Fix req.protocol for proxy-direct connectionsAshley Strebbefore adoptiona28b7a8
line 366why, one step back366 proto = this.get('X-Forwarded-Proto') || proto;pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
lines 367–383why, one step back367 return proto.split(/\s*,\s*/)[0];368});369370/**371 * Short-hand for:372 *373 * req.protocol == 'https'374 *375 * @return {Boolean}376 * @api public377 */378379req.__defineGetter__('secure', function(){380 return 'https' == this.protocol;381});382383/**improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
line 384why, one step back384 * Return the remote address from the trusted proxy.pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
line 385why, one step back385 *improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 386–388why, one step back386 * The is the remote address on the socket unless387 * "trust proxy" is set.388 *pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
lines 389–393why, one step back389 * @return {String}390 * @api public391 */392393req.__defineGetter__('ip', function(){improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 394–395why, one step back394 var trust = this.app.get('trust proxy fn');395 return proxyaddr(this, trust);pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
lines 396–398why, one step back396});397398/**improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
line 399why, one step back399 * When "trust proxy" is set, trusted proxy addresses + client.pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
lines 400–402why, one step back400 *401 * For example if the value were "client, proxy1, proxy2"402 * you would receive the array `["client", "proxy1", "proxy2"]`improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 403–404why, one step back403 * where "proxy2" is the furthest down-stream and "proxy1" and404 * "proxy2" were trusted.pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
lines 405–410why, one step back405 *406 * @return {Array}407 * @api public408 */409410req.__defineGetter__('ips', function(){improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 411–413why, one step back411 var trust = this.app.get('trust proxy fn');412 var addrs = proxyaddr.all(this, trust);413 return addrs.slice(1).reverse();pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
lines 414–429why, one step back414});415416/**417 * Return basic auth credentials.418 *419 * Examples:420 *421 * // http://tobi:hello@example.com422 * req.auth423 * // => { username: 'tobi', password: 'hello' }424 *425 * @return {Object} or undefined426 * @api public427 */428429req.__defineGetter__('auth', function(){Adjust wording on deprecation messagesDouglas Christopher Wilsonbefore adoptionf724730
line 430why, one step back430 deprecate('req.auth: Use basic-auth npm module instead');pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
lines 431–432why, one step back431432 // credentialsadd deprecation message to req.authDouglas Christopher Wilsonbefore adoptionf381f2d
lines 433–436why, one step back433 var creds = auth(this);434 if (!creds) return;435436 return { username: creds.name, password: creds.pass };pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
lines 437–475why, one step back437});438439/**440 * Return subdomains as an array.441 *442 * Subdomains are the dot-separated parts of the host before the main domain of443 * the app. By default, the domain of the app is assumed to be the last two444 * parts of the host. This can be changed by setting "subdomain offset".445 *446 * For example, if the domain is "tobi.ferrets.example.com":447 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.448 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.449 *450 * @return {Array}451 * @api public452 */453454req.__defineGetter__('subdomains', function(){455 var offset = this.app.get('subdomain offset');456 return (this.host || '')457 .split('.')458 .reverse()459 .slice(offset);460});461462/**463 * Short-hand for `url.parse(req.url).pathname`.464 *465 * @return {String}466 * @api public467 */468469req.__defineGetter__('path', function(){470 return parse(this).pathname;471});472473/**474 * Parse the "Host" header field hostname.475 *improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 476–479why, one step back476 * When the "trust proxy" setting trusts the socket477 * address, the "X-Forwarded-Host" header field will478 * be trusted.479 *pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
lines 480–484why, one step back480 * @return {String}481 * @api public482 */483484req.__defineGetter__('host', function(){improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 485–491why, one step back485 var trust = this.app.get('trust proxy fn');486 var host = this.get('X-Forwarded-Host');487488 if (!host || !trust(this.connection.remoteAddress)) {489 host = this.get('Host');490 }491pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
line 492why, one step back492 if (!host) return;improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 493–494why, one step back493494 // IPv6 literal supportMerge branch '3.5.x' into 3.xDouglas Christopher Wilsonbefore adoption66b38b5
lines 495–498why, one step back495 var offset = host[0] === '['496 ? host.indexOf(']') + 1497 : 0;498 var index = host.indexOf(':', offset);improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
line 499why, one step back499Merge branch '3.5.x' into 3.xDouglas Christopher Wilsonbefore adoption66b38b5
lines 500–502why, one step back500 return ~index501 ? host.substring(0, index)502 : host;pin marked devDep to protect out testsRoman Shtylmanbefore adoption89e7264
lines 503–552why, one step back503});504505/**506 * Check if the request is fresh, aka507 * Last-Modified and/or the ETag508 * still match.509 *510 * @return {Boolean}511 * @api public512 */513514req.__defineGetter__('fresh', function(){515 var method = this.method;516 var s = this.res.statusCode;517518 // GET or HEAD for weak freshness validation only519 if ('GET' != method && 'HEAD' != method) return false;520521 // 2xx or 304 as per rfc2616 14.26522 if ((s >= 200 && s < 300) || 304 == s) {523 return fresh(this.headers, this.res._headers);524 }525526 return false;527});528529/**530 * Check if the request is stale, aka531 * "Last-Modified" and / or the "ETag" for the532 * resource has changed.533 *534 * @return {Boolean}535 * @api public536 */537538req.__defineGetter__('stale', function(){539 return !this.fresh;540});541542/**543 * Check if the request was an _XMLHttpRequest_.544 *545 * @return {Boolean}546 * @api public547 */548549req.__defineGetter__('xhr', function(){550 var val = this.get('X-Requested-With') || '';551 return 'xmlhttprequest' == val.toLowerCase();552});