Skip to content
Myr

request.js

This file

Path

lib/request.js

558 lines · 12.2 KiB · JavaScript

Last changed by

Fix error in req.subdomains on empty hostDouglas Christopher Wilsonbefore adoption70767b1

History of this file

Take it

The walk stopped after 200 commits: lines older than d581592 point at it.

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 1–5why, one step back
1
2/**3 * Module dependencies.4 */5

add deprecation message to req.authDouglas Christopher Wilsonbefore adoptionf381f2d

lines 6–7why, one step back
6var auth = require('basic-auth');
7var deprecate = require('depd')('express');

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 8–12why, one step back
8var 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 back
13 , parse = require('parseurl')

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 14why, one step back
14 , proxyaddr = require('proxy-addr')

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

line 15why, one step back
15 , mime = connect.mime;

Support IP address host in req.subdomainsDouglas Christopher Wilsonbefore adoption2de6514

line 16why, one step back
16var isIP = require('net').isIP;

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 17–343why, one step back
17
18/**19 * Request prototype.20 */2122var req = exports = module.exports = {23 __proto__: http.IncomingMessage.prototype24};2526/**27 * Return request header.28 *29 * The `Referrer` header field is special-cased,30 * both `Referrer` and `Referer` are interchangeable.31 *32 * Examples:33 *34 * req.get('Content-Type');35 * // => "text/plain"36 *37 * req.get('content-type');38 * // => "text/plain"39 *40 * req.get('Something');41 * // => undefined42 *43 * Aliased as `req.header()`.44 *45 * @param {String} name46 * @return {String}47 * @api public48 */4950req.get =51req.header = function(name){52 switch (name = name.toLowerCase()) {53 case 'referer':54 case 'referrer':55 return this.headers.referrer56 || this.headers.referer;57 default:58 return this.headers[name];59 }60};6162/**63 * Check if the given `type(s)` is acceptable, returning64 * the best match when true, otherwise `undefined`, in which65 * case you should respond with 406 "Not Acceptable".66 *67 * The `type` value may be a single mime type string68 * such as "application/json", the extension name69 * such as "json", a comma-delimted list such as "json, html, text/plain",70 * an argument list such as `"json", "html", "text/plain"`,71 * or an array `["json", "html", "text/plain"]`. When a list72 * or array is given the _best_ match, if any is returned.73 *74 * Examples:75 *76 * // Accept: text/html77 * req.accepts('html');78 * // => "html"79 *80 * // Accept: text/*, application/json81 * req.accepts('html');82 * // => "html"83 * req.accepts('text/html');84 * // => "text/html"85 * req.accepts('json, text');86 * // => "json"87 * req.accepts('application/json');88 * // => "application/json"89 *90 * // Accept: text/*, application/json91 * req.accepts('image/png');92 * req.accepts('png');93 * // => undefined94 *95 * // Accept: text/*;q=.5, application/json96 * req.accepts(['html', 'json']);97 * req.accepts('html', 'json');98 * req.accepts('html, json');99 * // => "json"100 *101 * @param {String|Array} type(s)102 * @return {String}103 * @api public104 */105106req.accepts = function(type){107 var args = arguments.length > 1 ? [].slice.apply(arguments) : type;108 return utils.accepts(args, this.get('Accept'));109};110111/**112 * Check if the given `encoding` is accepted.113 *114 * @param {String} encoding115 * @return {Boolean}116 * @api public117 */118119req.acceptsEncoding = function(encoding){120 return !! ~this.acceptedEncodings.indexOf(encoding);121};122123/**124 * Check if the given `charset` is acceptable,125 * otherwise you should respond with 406 "Not Acceptable".126 *127 * @param {String} charset128 * @return {Boolean}129 * @api public130 */131132req.acceptsCharset = function(charset){133 var accepted = this.acceptedCharsets;134 return accepted.length135 ? !! ~accepted.indexOf(charset)136 : true;137};138139/**140 * Check if the given `lang` is acceptable,141 * otherwise you should respond with 406 "Not Acceptable".142 *143 * @param {String} lang144 * @return {Boolean}145 * @api public146 */147148req.acceptsLanguage = function(lang){149 var accepted = this.acceptedLanguages;150 return accepted.length151 ? !! ~accepted.indexOf(lang)152 : true;153};154155/**156 * Parse Range header field,157 * capping to the given `size`.158 *159 * Unspecified ranges such as "0-" require160 * knowledge of your resource length. In161 * the case of a byte range this is of course162 * the total number of bytes. If the Range163 * header field is not given `null` is returned,164 * `-1` when unsatisfiable, `-2` when syntactically invalid.165 *166 * NOTE: remember that ranges are inclusive, so167 * for example "Range: users=0-3" should respond168 * with 4 users when available, not 3.169 *170 * @param {Number} size171 * @return {Array}172 * @api public173 */174175req.range = function(size){176 var range = this.get('Range');177 if (!range) return;178 return parseRange(size, range);179};180181/**182 * Return an array of encodings.183 *184 * Examples:185 *186 * ['gzip', 'deflate']187 *188 * @return {Array}189 * @api public190 */191192req.__defineGetter__('acceptedEncodings', function(){193 var accept = this.get('Accept-Encoding');194 return accept195 ? accept.trim().split(/ *, */)196 : [];197});198199/**200 * Return an array of Accepted media types201 * ordered from highest quality to lowest.202 *203 * Examples:204 *205 * [ { value: 'application/json',206 * quality: 1,207 * type: 'application',208 * subtype: 'json' },209 * { value: 'text/html',210 * quality: 0.5,211 * type: 'text',212 * subtype: 'html' } ]213 *214 * @return {Array}215 * @api public216 */217218req.__defineGetter__('accepted', function(){219 var accept = this.get('Accept');220 return accept221 ? utils.parseAccept(accept)222 : [];223});224225/**226 * Return an array of Accepted languages227 * ordered from highest quality to lowest.228 *229 * Examples:230 *231 * Accept-Language: en;q=.5, en-us232 * ['en-us', 'en']233 *234 * @return {Array}235 * @api public236 */237238req.__defineGetter__('acceptedLanguages', function(){239 var accept = this.get('Accept-Language');240 return accept241 ? utils242 .parseParams(accept)243 .map(function(obj){244 return obj.value;245 })246 : [];247});248249/**250 * Return an array of Accepted charsets251 * ordered from highest quality to lowest.252 *253 * Examples:254 *255 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8256 * ['unicode-1-1', 'iso-8859-5']257 *258 * @return {Array}259 * @api public260 */261262req.__defineGetter__('acceptedCharsets', function(){263 var accept = this.get('Accept-Charset');264 return accept265 ? utils266 .parseParams(accept)267 .map(function(obj){268 return obj.value;269 })270 : [];271});272273/**274 * Return the value of param `name` when present or `defaultValue`.275 *276 * - Checks route placeholders, ex: _/user/:id_277 * - Checks body params, ex: id=12, {"id":12}278 * - Checks query string params, ex: ?id=12279 *280 * To utilize request bodies, `req.body`281 * should be an object. This can be done by using282 * the `connect.bodyParser()` middleware.283 *284 * @param {String} name285 * @param {Mixed} [defaultValue]286 * @return {String}287 * @api public288 */289290req.param = function(name, defaultValue){291 var params = this.params || {};292 var body = this.body || {};293 var query = this.query || {};294 if (null != params[name] && params.hasOwnProperty(name)) return params[name];295 if (null != body[name]) return body[name];296 if (null != query[name]) return query[name];297 return defaultValue;298};299300/**301 * Check if the incoming request contains the "Content-Type"302 * header field, and it contains the give mime `type`.303 *304 * Examples:305 *306 * // With Content-Type: text/html; charset=utf-8307 * req.is('html');308 * req.is('text/html');309 * req.is('text/*');310 * // => true311 *312 * // When Content-Type is application/json313 * req.is('json');314 * req.is('application/json');315 * req.is('application/*');316 * // => true317 *318 * req.is('html');319 * // => false320 *321 * @param {String} type322 * @return {Boolean}323 * @api public324 */325326req.is = function(type){327 var ct = this.get('Content-Type');328 if (!ct) return false;329 ct = ct.split(';')[0];330 if (!~type.indexOf('/')) type = mime.lookup(type);331 if (~type.indexOf('*')) {332 type = type.split('/');333 ct = ct.split('/');334 if ('*' == type[0] && type[1] == ct[1]) return true;335 if ('*' == type[1] && type[0] == ct[0]) return true;336 return false;337 }338 return !! ~ct.indexOf(type);339};340341/**342 * Return the protocol string "http" or "https"343 * when requested with TLS. When the "trust proxy"

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 344why, one step back
344 * setting trusts the socket address, the

Fix req.protocol for proxy-direct connectionsAshley Strebbefore adoptiona28b7a8

lines 345–347why, one step back
345 * "X-Forwarded-Proto" header field will be trusted
346 * and used if present.347 *

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 348–349why, one step back
348 * If you're running behind a reverse proxy that
349 * supplies https for you this may be enabled.

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 350–355why, one step back
350 *
351 * @return {String}352 * @api public353 */354355req.__defineGetter__('protocol', function(){

Fix req.protocol for proxy-direct connectionsAshley Strebbefore adoptiona28b7a8

lines 356–358why, one step back
356 var proto = this.connection.encrypted
357 ? 'https'358 : 'http';

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 359–361why, one step back
359 var trust = this.app.get('trust proxy fn');
360361 if (!trust(this.connection.remoteAddress)) {

Fix req.protocol for proxy-direct connectionsAshley Strebbefore adoptiona28b7a8

line 362why, one step back
362 return proto;

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 363–366why, one step back
363 }
364365 // Note: X-Forwarded-Proto is normally only ever a366 // single value, but this is to be safe.

Fix req.protocol for proxy-direct connectionsAshley Strebbefore adoptiona28b7a8

line 367why, one step back
367 proto = this.get('X-Forwarded-Proto') || proto;

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 368–384why, one step back
368 return proto.split(/\s*,\s*/)[0];
369});370371/**372 * Short-hand for:373 *374 * req.protocol == 'https'375 *376 * @return {Boolean}377 * @api public378 */379380req.__defineGetter__('secure', function(){381 return 'https' == this.protocol;382});383384/**

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 385why, one step back
385 * Return the remote address from the trusted proxy.

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

line 386why, one step back
386 *

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 387–389why, one step back
387 * The is the remote address on the socket unless
388 * "trust proxy" is set.389 *

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 390–394why, one step back
390 * @return {String}
391 * @api public392 */393394req.__defineGetter__('ip', function(){

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 395–396why, one step back
395 var trust = this.app.get('trust proxy fn');
396 return proxyaddr(this, trust);

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 397–399why, one step back
397});
398399/**

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 400why, one step back
400 * When "trust proxy" is set, trusted proxy addresses + client.

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 401–403why, one step back
401 *
402 * For example if the value were "client, proxy1, proxy2"403 * you would receive the array `["client", "proxy1", "proxy2"]`

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 404–405why, one step back
404 * where "proxy2" is the furthest down-stream and "proxy1" and
405 * "proxy2" were trusted.

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 406–411why, one step back
406 *
407 * @return {Array}408 * @api public409 */410411req.__defineGetter__('ips', function(){

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 412–414why, one step back
412 var trust = this.app.get('trust proxy fn');
413 var addrs = proxyaddr.all(this, trust);414 return addrs.slice(1).reverse();

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 415–430why, one step back
415});
416417/**418 * Return basic auth credentials.419 *420 * Examples:421 *422 * // http://tobi:hello@example.com423 * req.auth424 * // => { username: 'tobi', password: 'hello' }425 *426 * @return {Object} or undefined427 * @api public428 */429430req.__defineGetter__('auth', function(){

Adjust wording on deprecation messagesDouglas Christopher Wilsonbefore adoptionf724730

line 431why, one step back
431 deprecate('req.auth: Use basic-auth npm module instead');

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 432–433why, one step back
432
433 // credentials

add deprecation message to req.authDouglas Christopher Wilsonbefore adoptionf381f2d

lines 434–437why, one step back
434 var creds = auth(this);
435 if (!creds) return;436437 return { username: creds.name, password: creds.pass };

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 438–455why, one step back
438});
439440/**441 * Return subdomains as an array.442 *443 * Subdomains are the dot-separated parts of the host before the main domain of444 * the app. By default, the domain of the app is assumed to be the last two445 * parts of the host. This can be changed by setting "subdomain offset".446 *447 * For example, if the domain is "tobi.ferrets.example.com":448 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.449 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.450 *451 * @return {Array}452 * @api public453 */454455req.__defineGetter__('subdomains', function(){

Support X-Forwarded-Host in req.subdomainsDouglas Christopher Wilsonbefore adoptiond07c063

line 456why, one step back
456 var host = this.host;

Fix error in req.subdomains on empty hostDouglas Christopher Wilsonbefore adoption70767b1

lines 457–459why, one step back
457
458 if (!host) return [];459

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

line 460why, one step back
460 var offset = this.app.get('subdomain offset');

Support IP address host in req.subdomainsDouglas Christopher Wilsonbefore adoption2de6514

lines 461–463why, one step back
461 var subdomains = !isIP(host)
462 ? host.split('.').reverse()463 : [host];

Support X-Forwarded-Host in req.subdomainsDouglas Christopher Wilsonbefore adoptiond07c063

lines 464–465why, one step back
464
465 return subdomains.slice(offset);

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 466–481why, one step back
466});
467468/**469 * Short-hand for `url.parse(req.url).pathname`.470 *471 * @return {String}472 * @api public473 */474475req.__defineGetter__('path', function(){476 return parse(this).pathname;477});478479/**480 * Parse the "Host" header field hostname.481 *

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 482–485why, one step back
482 * When the "trust proxy" setting trusts the socket
483 * address, the "X-Forwarded-Host" header field will484 * be trusted.485 *

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 486–490why, one step back
486 * @return {String}
487 * @api public488 */489490req.__defineGetter__('host', function(){

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 491–497why, one step back
491 var trust = this.app.get('trust proxy fn');
492 var host = this.get('X-Forwarded-Host');493494 if (!host || !trust(this.connection.remoteAddress)) {495 host = this.get('Host');496 }497

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

line 498why, one step back
498 if (!host) return;

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 499–500why, one step back
499
500 // IPv6 literal support

Merge branch '3.5.x' into 3.xDouglas Christopher Wilsonbefore adoption66b38b5

lines 501–504why, one step back
501 var offset = host[0] === '['
502 ? host.indexOf(']') + 1503 : 0;504 var index = host.indexOf(':', offset);

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 505why, one step back
505

Merge branch '3.5.x' into 3.xDouglas Christopher Wilsonbefore adoption66b38b5

lines 506–508why, one step back
506 return ~index
507 ? host.substring(0, index)508 : host;

3.5.2Douglas Christopher Wilsonbefore adoptiond581592

lines 509–558why, one step back
509});
510511/**512 * Check if the request is fresh, aka513 * Last-Modified and/or the ETag514 * still match.515 *516 * @return {Boolean}517 * @api public518 */519520req.__defineGetter__('fresh', function(){521 var method = this.method;522 var s = this.res.statusCode;523524 // GET or HEAD for weak freshness validation only525 if ('GET' != method && 'HEAD' != method) return false;526527 // 2xx or 304 as per rfc2616 14.26528 if ((s >= 200 && s < 300) || 304 == s) {529 return fresh(this.headers, this.res._headers);530 }531532 return false;533});534535/**536 * Check if the request is stale, aka537 * "Last-Modified" and / or the "ETag" for the538 * resource has changed.539 *540 * @return {Boolean}541 * @api public542 */543544req.__defineGetter__('stale', function(){545 return !this.fresh;546});547548/**549 * Check if the request was an _XMLHttpRequest_.550 *551 * @return {Boolean}552 * @api public553 */554555req.__defineGetter__('xhr', function(){556 var val = this.get('X-Requested-With') || '';557 return 'xmlhttprequest' == val.toLowerCase();558});