Skip to content
Myr

request.js

This file

Path

lib/request.js

529 lines · 11.6 KiB · JavaScript

Last changed by

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption752b5f7

History of this file

Take it

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

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 1–31why, one step back
1
2/**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"

move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa

line 32why, one step back
32 *

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 33–34why, one step back
33 * req.get('content-type');
34 * // => "text/plain"

move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa

line 35why, one step back
35 *

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 36–41why, one step back
36 * req.get('Something');
37 * // => undefined38 *39 * Aliased as `req.header()`.40 *41 * @param {String} name

move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa

line 42why, one step back
42 * @return {String}

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 43–45why, one step back
43 * @api public
44 */45

move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa

line 46why, one step back
46req.get =

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 47–65why, one step back
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 back
66 * an argument list such as `"json", "html", "text/plain"`,

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 67–70why, one step back
67 * or an array `["json", "html", "text/plain"]`. When a list
68 * or array is given the _best_ match, if any is returned.69 *70 * Examples:

move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa

line 71why, one step back
71 *

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 72–92why, one step back
72 * // Accept: text/html
73 * 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 back
93 * req.accepts('html', 'json');

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 94–102why, one step back
94 * 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 back
103 var args = arguments.length > 1 ? [].slice.apply(arguments) : type;
104 return utils.accepts(args, this.get('Accept'));

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 105–107why, one step back
105};
106107/**

add req.acceptsEncoding(name)TJ Holowaychukbefore adoption2e53cb7

lines 108–115why, one step back
108 * 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 back
116 return !! ~this.acceptedEncodings.indexOf(encoding);

add req.acceptsEncoding(name)TJ Holowaychukbefore adoption2e53cb7

lines 117–119why, one step back
117};
118119/**

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 120–130why, one step back
120 * 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.length

return actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b

line 131why, one step back
131 ? !! ~accepted.indexOf(charset)

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 132–146why, one step back
132 : 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.length

return actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b

line 147why, one step back
147 ? !! ~accepted.indexOf(lang)

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 148–177why, one step back
148 : 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 back
178 * 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/**

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 196–237why, one step back
196 * Return an array of Accepted media types
197 * 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 ? utils

add support for custom Accept parametersPavel Brylovbefore adoption9e684d4

line 238why, one step back
238 .parseParams(accept)

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 239–261why, one step back
239 .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 ? utils

add support for custom Accept parametersPavel Brylovbefore adoption9e684d4

line 262why, one step back
262 .parseParams(accept)

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 263–280why, one step back
263 .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} name

docsTJ Holowaychukbefore adoptiond1bafa0

line 281why, one step back
281 * @param {Mixed} [defaultValue]

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 282–296why, one step back
282 * @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/**

move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa

line 297why, one step back
297 * Check if the incoming request contains the "Content-Type"

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 298–306why, one step back
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 * // => true

move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa

line 307why, one step back
307 *

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 308–312why, one step back
308 * // When Content-Type is application/json
309 * req.is('json');310 * req.is('application/json');311 * req.is('application/*');312 * // => true

move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa

line 313why, one step back
313 *

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 314–315why, one step back
314 * req.is('html');
315 * // => false

move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa

line 316why, one step back
316 *

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 317–338why, one step back
317 * @param {String} type
318 * @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"

move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa

line 339why, one step back
339 * when requested with TLS. When the "trust proxy"

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 340–350why, one step back
340 * setting is enabled the "X-Forwarded-Proto" header
341 * 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 back
351 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];

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 355–427why, one step back
355});
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 // credentials

Merge pull request #1462 from gmethvin/colon_authTJ Holowaychukbefore adoption480d006

lines 428–430why, one step back
428 auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/);
429 if (!auth) return;430 return { username: auth[1], password: auth[2] };

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 431–435why, one step back
431});
432433/**434 * Return subdomains as an array.435 *

Merge pull request #1475 from gmethvin/subdomain_offsetTJ Holowaychukbefore adoption5beb1c4

lines 436–438why, one step back
436 * Subdomains are the dot-separated parts of the host before the main domain of
437 * 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".

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

line 439why, one step back
439 *

Merge pull request #1475 from gmethvin/subdomain_offsetTJ Holowaychukbefore adoption5beb1c4

lines 440–443why, one step back
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 *

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 444–448why, one step back
444 * @return {Array}
445 * @api public446 */447448req.__defineGetter__('subdomains', function(){

Merge pull request #1475 from gmethvin/subdomain_offsetTJ Holowaychukbefore adoption5beb1c4

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

fix `req.subdomains` when no Host is presentTJ Holowaychukbefore adoption8559c0e

line 450why, one step back
450 return (this.host || '')

change req.subdomain styling backTJ Holowaychukbefore adoptione3ac2c5

lines 451–453why, one step back
451 .split('.')
452 .reverse()453 .slice(offset);

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 454–474why, one step back
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(){

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71

line 475why, one step back
475 var trustProxy = this.app.get('trust proxy');

refactor req.hostTJ Holowaychukbefore adoption4a1fa58

lines 476–477why, one step back
476 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 back
478 if (!host) return;

refactor req.hostTJ Holowaychukbefore adoption4a1fa58

line 479why, one step back
479 return host.split(':')[0];

fix route chaining regression. Closes #1397TJ Holowaychukbefore adoptiona7ca381

lines 480–529why, one step back
480});
481482/**483 * Check if the request is fresh, aka484 * Last-Modified and/or the ETag485 * still match.486 *487 * @return {Boolean}488 * @api public489 */490491req.__defineGetter__('fresh', function(){492 var method = this.method;493 var s = this.res.statusCode;494495 // GET or HEAD for weak freshness validation only496 if ('GET' != method && 'HEAD' != method) return false;497498 // 2xx or 304 as per rfc2616 14.26499 if ((s >= 200 && s < 300) || 304 == s) {500 return fresh(this.headers, this.res._headers);501 }502503 return false;504});505506/**507 * Check if the request is stale, aka508 * "Last-Modified" and / or the "ETag" for the509 * resource has changed.510 *511 * @return {Boolean}512 * @api public513 */514515req.__defineGetter__('stale', function(){516 return !this.fresh;517});518519/**520 * Check if the request was an _XMLHttpRequest_.521 *522 * @return {Boolean}523 * @api public524 */525526req.__defineGetter__('xhr', function(){527 var val = this.get('X-Requested-With') || '';528 return 'xmlhttprequest' == val.toLowerCase();529});