request.js
This file
Path
lib/request.js
526 lines · 11.4 KiB · JavaScript
Last changed by
return actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b
History of this fileTake it
The walk stopped after 200 commits: lines older than 42fd29e point at it.
deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 1–31why, one step back12/**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 back32 *deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 33–34why, one step back33 * req.get('content-type');34 * // => "text/plain"move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 35why, one step back35 *deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 36–41why, one step back36 * req.get('Something');37 * // => undefined38 *39 * Aliased as `req.header()`.40 *41 * @param {String} namemove "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 42why, one step back42 * @return {String}deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 43–45why, one step back43 * @api public44 */45move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 46why, one step back46req.get =deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 47–69why, one step back47req.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",66 * or an array `["json", "html", "text/plain"]`. When a list67 * or array is given the _best_ match, if any is returned.68 *69 * Examples:move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 70why, one step back70 *deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 71–104why, one step back71 * // Accept: text/html72 * req.accepts('html');73 * // => "html"74 *75 * // Accept: text/*, application/json76 * req.accepts('html');77 * // => "html"78 * req.accepts('text/html');79 * // => "text/html"80 * req.accepts('json, text');81 * // => "json"82 * req.accepts('application/json');83 * // => "application/json"84 *85 * // Accept: text/*, application/json86 * req.accepts('image/png');87 * req.accepts('png');88 * // => undefined89 *90 * // Accept: text/*;q=.5, application/json91 * req.accepts(['html', 'json']);92 * req.accepts('html, json');93 * // => "json"94 *95 * @param {String|Array} type(s)96 * @return {String}97 * @api public98 */99100req.accepts = function(type){101 return utils.accepts(type, this.get('Accept'));102};103104/**add req.acceptsEncoding(name)TJ Holowaychukbefore adoption2e53cb7
lines 105–112why, one step back105 * Check if the given `encoding` is accepted.106 *107 * @param {String} encoding108 * @return {Boolean}109 * @api public110 */111112req.acceptsEncoding = function(encoding){return actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b
line 113why, one step back113 return !! ~this.acceptedEncodings.indexOf(encoding);add req.acceptsEncoding(name)TJ Holowaychukbefore adoption2e53cb7
lines 114–116why, one step back114};115116/**deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 117–127why, one step back117 * Check if the given `charset` is acceptable,118 * otherwise you should respond with 406 "Not Acceptable".119 *120 * @param {String} charset121 * @return {Boolean}122 * @api public123 */124125req.acceptsCharset = function(charset){126 var accepted = this.acceptedCharsets;127 return accepted.lengthreturn actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b
line 128why, one step back128 ? !! ~accepted.indexOf(charset)deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 129–143why, one step back129 : true;130};131132/**133 * Check if the given `lang` is acceptable,134 * otherwise you should respond with 406 "Not Acceptable".135 *136 * @param {String} lang137 * @return {Boolean}138 * @api public139 */140141req.acceptsLanguage = function(lang){142 var accepted = this.acceptedLanguages;143 return accepted.lengthreturn actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b
line 144why, one step back144 ? !! ~accepted.indexOf(lang)deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 145–174why, one step back145 : true;146};147148/**149 * Parse Range header field,150 * capping to the given `size`.151 *152 * Unspecified ranges such as "0-" require153 * knowledge of your resource length. In154 * the case of a byte range this is of course155 * the total number of bytes. If the Range156 * header field is not given `null` is returned,157 * `-1` when unsatisfiable, `-2` when syntactically invalid.158 *159 * NOTE: remember that ranges are inclusive, so160 * for example "Range: users=0-3" should respond161 * with 4 users when available, not 3.162 *163 * @param {Number} size164 * @return {Array}165 * @api public166 */167168req.range = function(size){169 var range = this.get('Range');170 if (!range) return;171 return parseRange(size, range);172};173174/**add req.acceptedEncodingsTJ Holowaychukbefore adoption3b1597d
lines 175–192why, one step back175 * Return an array of encodings.176 *177 * Examples:178 *179 * ['gzip', 'deflate']180 *181 * @return {Array}182 * @api public183 */184185req.__defineGetter__('acceptedEncodings', function(){186 var accept = this.get('Accept-Encoding');187 return accept188 ? accept.trim().split(/ *, */)189 : [];190});191192/**deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 193–234why, one step back193 * Return an array of Accepted media types194 * ordered from highest quality to lowest.195 *196 * Examples:197 *198 * [ { value: 'application/json',199 * quality: 1,200 * type: 'application',201 * subtype: 'json' },202 * { value: 'text/html',203 * quality: 0.5,204 * type: 'text',205 * subtype: 'html' } ]206 *207 * @return {Array}208 * @api public209 */210211req.__defineGetter__('accepted', function(){212 var accept = this.get('Accept');213 return accept214 ? utils.parseAccept(accept)215 : [];216});217218/**219 * Return an array of Accepted languages220 * ordered from highest quality to lowest.221 *222 * Examples:223 *224 * Accept-Language: en;q=.5, en-us225 * ['en-us', 'en']226 *227 * @return {Array}228 * @api public229 */230231req.__defineGetter__('acceptedLanguages', function(){232 var accept = this.get('Accept-Language');233 return accept234 ? utilsadd support for custom Accept parametersPavel Brylovbefore adoption9e684d4
line 235why, one step back235 .parseParams(accept)deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 236–258why, one step back236 .map(function(obj){237 return obj.value;238 })239 : [];240});241242/**243 * Return an array of Accepted charsets244 * ordered from highest quality to lowest.245 *246 * Examples:247 *248 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8249 * ['unicode-1-1', 'iso-8859-5']250 *251 * @return {Array}252 * @api public253 */254255req.__defineGetter__('acceptedCharsets', function(){256 var accept = this.get('Accept-Charset');257 return accept258 ? utilsadd support for custom Accept parametersPavel Brylovbefore adoption9e684d4
line 259why, one step back259 .parseParams(accept)deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 260–277why, one step back260 .map(function(obj){261 return obj.value;262 })263 : [];264});265266/**267 * Return the value of param `name` when present or `defaultValue`.268 *269 * - Checks route placeholders, ex: _/user/:id_270 * - Checks body params, ex: id=12, {"id":12}271 * - Checks query string params, ex: ?id=12272 *273 * To utilize request bodies, `req.body`274 * should be an object. This can be done by using275 * the `connect.bodyParser()` middleware.276 *277 * @param {String} namedocsTJ Holowaychukbefore adoptiond1bafa0
line 278why, one step back278 * @param {Mixed} [defaultValue]deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 279–293why, one step back279 * @return {String}280 * @api public281 */282283req.param = function(name, defaultValue){284 var params = this.params || {};285 var body = this.body || {};286 var query = this.query || {};287 if (null != params[name] && params.hasOwnProperty(name)) return params[name];288 if (null != body[name]) return body[name];289 if (null != query[name]) return query[name];290 return defaultValue;291};292293/**move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 294why, one step back294 * Check if the incoming request contains the "Content-Type"deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 295–303why, one step back295 * header field, and it contains the give mime `type`.296 *297 * Examples:298 *299 * // With Content-Type: text/html; charset=utf-8300 * req.is('html');301 * req.is('text/html');302 * req.is('text/*');303 * // => truemove "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 304why, one step back304 *deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 305–309why, one step back305 * // When Content-Type is application/json306 * req.is('json');307 * req.is('application/json');308 * req.is('application/*');309 * // => truemove "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 310why, one step back310 *deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 311–312why, one step back311 * req.is('html');312 * // => falsemove "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 313why, one step back313 *deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 314–335why, one step back314 * @param {String} type315 * @return {Boolean}316 * @api public317 */318319req.is = function(type){320 var ct = this.get('Content-Type');321 if (!ct) return false;322 ct = ct.split(';')[0];323 if (!~type.indexOf('/')) type = mime.lookup(type);324 if (~type.indexOf('*')) {325 type = type.split('/');326 ct = ct.split('/');327 if ('*' == type[0] && type[1] == ct[1]) return true;328 if ('*' == type[1] && type[0] == ct[0]) return true;329 return false;330 }331 return !! ~ct.indexOf(type);332};333334/**335 * Return the protocol string "http" or "https"move "subdomain offset" defaulting to configTJ Holowaychukbefore adoptioncd54faa
line 336why, one step back336 * when requested with TLS. When the "trust proxy"deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 337–347why, one step back337 * setting is enabled the "X-Forwarded-Proto" header338 * field will be trusted. If you're running behind339 * a reverse proxy that supplies https for you this340 * may be enabled.341 *342 * @return {String}343 * @api public344 */345346req.__defineGetter__('protocol', function(){347 var trustProxy = this.app.get('trust proxy');add support for multiple X-Forwarded-Proto values. Closes #1646TJ Holowaychukbefore adoption8ab4408
lines 348–351why, one step back348 if (this.connection.encrypted) return 'https';349 if (!trustProxy) return 'http';350 var proto = this.get('X-Forwarded-Proto') || 'http';351 return proto.split(/\s*,\s*/)[0];deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 352–408why, one step back352});353354/**355 * Short-hand for:356 *357 * req.protocol == 'https'358 *359 * @return {Boolean}360 * @api public361 */362363req.__defineGetter__('secure', function(){364 return 'https' == this.protocol;365});366367/**368 * Return the remote address, or when369 * "trust proxy" is `true` return370 * the upstream addr.371 *372 * @return {String}373 * @api public374 */375376req.__defineGetter__('ip', function(){377 return this.ips[0] || this.connection.remoteAddress;378});379380/**381 * When "trust proxy" is `true`, parse382 * the "X-Forwarded-For" ip address list.383 *384 * For example if the value were "client, proxy1, proxy2"385 * you would receive the array `["client", "proxy1", "proxy2"]`386 * where "proxy2" is the furthest down-stream.387 *388 * @return {Array}389 * @api public390 */391392req.__defineGetter__('ips', function(){393 var trustProxy = this.app.get('trust proxy');394 var val = this.get('X-Forwarded-For');395 return trustProxy && val396 ? val.split(/ *, */)397 : [];398});399400/**401 * Return basic auth credentials.402 *403 * Examples:404 *405 * // http://tobi:hello@example.com406 * req.auth407 * // => { username: 'tobi', password: 'hello' }408 *add req.auth test coverageTJ Holowaychukbefore adoption7bf4ad3
line 409why, one step back409 * @return {Object} or undefineddeprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 410–415why, one step back410 * @api public411 */412413req.__defineGetter__('auth', function(){414 // missing415 var auth = this.get('Authorization');add req.auth test coverageTJ Holowaychukbefore adoption7bf4ad3
line 416why, one step back416 if (!auth) return;deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 417–418why, one step back417418 // malformedadd "Basic" check to req.authTJ Holowaychukbefore adoptiond6cb449
lines 419–422why, one step back419 var parts = auth.split(' ');420 if ('basic' != parts[0].toLowerCase()) return;421 if (!parts[1]) return;422 auth = parts[1];deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 423–424why, one step back423424 // credentialsMerge pull request #1462 from gmethvin/colon_authTJ Holowaychukbefore adoption480d006
lines 425–427why, one step back425 auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/);426 if (!auth) return;427 return { username: auth[1], password: auth[2] };deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 428–432why, one step back428});429430/**431 * Return subdomains as an array.432 *Merge pull request #1475 from gmethvin/subdomain_offsetTJ Holowaychukbefore adoption5beb1c4
lines 433–435why, one step back433 * Subdomains are the dot-separated parts of the host before the main domain of434 * the app. By default, the domain of the app is assumed to be the last two435 * parts of the host. This can be changed by setting "subdomain offset".deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
line 436why, one step back436 *Merge pull request #1475 from gmethvin/subdomain_offsetTJ Holowaychukbefore adoption5beb1c4
lines 437–440why, one step back437 * For example, if the domain is "tobi.ferrets.example.com":438 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.439 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.440 *deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 441–445why, one step back441 * @return {Array}442 * @api public443 */444445req.__defineGetter__('subdomains', function(){Merge pull request #1475 from gmethvin/subdomain_offsetTJ Holowaychukbefore adoption5beb1c4
line 446why, one step back446 var offset = this.app.get('subdomain offset');fix `req.subdomains` when no Host is presentTJ Holowaychukbefore adoption8559c0e
line 447why, one step back447 return (this.host || '')change req.subdomain styling backTJ Holowaychukbefore adoptione3ac2c5
lines 448–450why, one step back448 .split('.')449 .reverse()450 .slice(offset);deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 451–471why, one step back451});452453/**454 * Short-hand for `url.parse(req.url).pathname`.455 *456 * @return {String}457 * @api public458 */459460req.__defineGetter__('path', function(){461 return parse(this).pathname;462});463464/**465 * Parse the "Host" header field hostname.466 *467 * @return {String}468 * @api public469 */470471req.__defineGetter__('host', function(){Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption6654b71
line 472why, one step back472 var trustProxy = this.app.get('trust proxy');refactor req.hostTJ Holowaychukbefore adoption4a1fa58
lines 473–474why, one step back473 var host = trustProxy && this.get('X-Forwarded-Host');474 host = host || this.get('Host');fix `req.host` when no Host is present, return undefinedTJ Holowaychukbefore adoption06ead58
line 475why, one step back475 if (!host) return;refactor req.hostTJ Holowaychukbefore adoption4a1fa58
line 476why, one step back476 return host.split(':')[0];deprecate .createServer() & remove old stale examplesTJ Holowaychukbefore adoption42fd29e
lines 477–526why, one step back477});478479/**480 * Check if the request is fresh, aka481 * Last-Modified and/or the ETag482 * still match.483 *484 * @return {Boolean}485 * @api public486 */487488req.__defineGetter__('fresh', function(){489 var method = this.method;490 var s = this.res.statusCode;491492 // GET or HEAD for weak freshness validation only493 if ('GET' != method && 'HEAD' != method) return false;494495 // 2xx or 304 as per rfc2616 14.26496 if ((s >= 200 && s < 300) || 304 == s) {497 return fresh(this.headers, this.res._headers);498 }499500 return false;501});502503/**504 * Check if the request is stale, aka505 * "Last-Modified" and / or the "ETag" for the506 * resource has changed.507 *508 * @return {Boolean}509 * @api public510 */511512req.__defineGetter__('stale', function(){513 return !this.fresh;514});515516/**517 * Check if the request was an _XMLHttpRequest_.518 *519 * @return {Boolean}520 * @api public521 */522523req.__defineGetter__('xhr', function(){524 var val = this.get('X-Requested-With') || '';525 return 'xmlhttprequest' == val.toLowerCase();526});