request.js
This file
Path
lib/request.js
427 lines · 9.6 KiB · JavaScript
Last changed by
refactor to use basic-authJonathan Ongbefore adoption3cf7b2e
History of this fileTake it
The walk stopped after 200 commits: lines older than f8a33d1 point at it.
refactorTJ Holowaychukbefore adoptionf8a33d1
lines 1–5why, one step back12/**3 * Module dependencies.4 */5refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 6–7why, one step back6var accepts = require('accepts');7var typeis = require('type-is');refactor to use basic-authJonathan Ongbefore adoption3cf7b2e
lines 8–13why, one step back8var basicAuth = require('basic-auth');9var http = require('http');10var fresh = require('fresh');11var parseRange = require('range-parser');12var utils = require('./utils');13var parse = utils.parseUrl;refactorTJ Holowaychukbefore adoptionf8a33d1
lines 14–59why, one step back1415/**16 * Request prototype.17 */1819var req = exports = module.exports = {20 __proto__: http.IncomingMessage.prototype21};2223/**24 * Return request header.25 *26 * The `Referrer` header field is special-cased,27 * both `Referrer` and `Referer` are interchangeable.28 *29 * Examples:30 *31 * req.get('Content-Type');32 * // => "text/plain"33 *34 * req.get('content-type');35 * // => "text/plain"36 *37 * req.get('Something');38 * // => undefined39 *40 * Aliased as `req.header()`.41 *42 * @param {String} name43 * @return {String}44 * @api public45 */4647req.get =48req.header = function(name){49 switch (name = name.toLowerCase()) {50 case 'referer':51 case 'referrer':52 return this.headers.referrer53 || this.headers.referer;54 default:55 return this.headers[name];56 }57};5859/**refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 60–61why, one step back60 * To do: update docs.61 *refactorTJ Holowaychukbefore adoptionf8a33d1
lines 62–68why, one step back62 * 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"`,refactorTJ Holowaychukbefore adoptionf8a33d1
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');refactorTJ Holowaychukbefore adoptionf8a33d1
lines 97–104why, one step back97 * req.accepts('html, json');98 * // => "json"99 *100 * @param {String|Array} type(s)101 * @return {String}102 * @api public103 */104refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 105–107why, one step back105req.accepts = function(){106 var accept = accepts(this);107 return accept.types.apply(accept, arguments);refactorTJ Holowaychukbefore adoptionf8a33d1
lines 108–117why, one step back108};109110/**111 * Check if the given `encoding` is accepted.112 *113 * @param {String} encoding114 * @return {Boolean}115 * @api public116 */117refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 118–121why, one step back118req.acceptsEncoding = // backwards compatibility119req.acceptsEncodings = function(){120 var accept = accepts(this);121 return accept.encodings.apply(accept, arguments);refactorTJ Holowaychukbefore adoptionf8a33d1
lines 122–124why, one step back122};123124/**refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 125–126why, one step back125 * To do: update docs.126 *refactorTJ Holowaychukbefore adoptionf8a33d1
lines 127–134why, one step back127 * Check if the given `charset` is acceptable,128 * otherwise you should respond with 406 "Not Acceptable".129 *130 * @param {String} charset131 * @return {Boolean}132 * @api public133 */134refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 135–138why, one step back135req.acceptsCharset = // backwards compatibility136req.acceptsCharsets = function(){137 var accept = accepts(this);138 return accept.charsets.apply(accept, arguments);refactorTJ Holowaychukbefore adoptionf8a33d1
lines 139–141why, one step back139};140141/**refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 142–143why, one step back142 * To do: update docs.143 *refactorTJ Holowaychukbefore adoptionf8a33d1
lines 144–151why, one step back144 * Check if the given `lang` is acceptable,145 * otherwise you should respond with 406 "Not Acceptable".146 *147 * @param {String} lang148 * @return {Boolean}149 * @api public150 */151refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
line 152why, one step back152req.acceptsLanguage = // backwards compatibilitysome jshint cleanupJonathan Ongbefore adoption5572897
line 153why, one step back153req.acceptsLanguages = function(){refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 154–155why, one step back154 var accept = accepts(this);155 return accept.languages.apply(accept, arguments);refactorTJ Holowaychukbefore adoptionf8a33d1
lines 156–192why, one step back156};157158/**159 * Parse Range header field,160 * capping to the given `size`.161 *162 * Unspecified ranges such as "0-" require163 * knowledge of your resource length. In164 * the case of a byte range this is of course165 * the total number of bytes. If the Range166 * header field is not given `null` is returned,167 * `-1` when unsatisfiable, `-2` when syntactically invalid.168 *169 * NOTE: remember that ranges are inclusive, so170 * for example "Range: users=0-3" should respond171 * with 4 users when available, not 3.172 *173 * @param {Number} size174 * @return {Array}175 * @api public176 */177178req.range = function(size){179 var range = this.get('Range');180 if (!range) return;181 return parseRange(size, range);182};183184/**185 * Return the value of param `name` when present or `defaultValue`.186 *187 * - Checks route placeholders, ex: _/user/:id_188 * - Checks body params, ex: id=12, {"id":12}189 * - Checks query string params, ex: ?id=12190 *191 * To utilize request bodies, `req.body`192 * should be an object. This can be done by usingremove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
line 193why, one step back193 * the `bodyParser()` middleware.refactorTJ Holowaychukbefore adoptionf8a33d1
lines 194–236why, one step back194 *195 * @param {String} name196 * @param {Mixed} [defaultValue]197 * @return {String}198 * @api public199 */200201req.param = function(name, defaultValue){202 var params = this.params || {};203 var body = this.body || {};204 var query = this.query || {};205 if (null != params[name] && params.hasOwnProperty(name)) return params[name];206 if (null != body[name]) return body[name];207 if (null != query[name]) return query[name];208 return defaultValue;209};210211/**212 * Check if the incoming request contains the "Content-Type"213 * header field, and it contains the give mime `type`.214 *215 * Examples:216 *217 * // With Content-Type: text/html; charset=utf-8218 * req.is('html');219 * req.is('text/html');220 * req.is('text/*');221 * // => true222 *223 * // When Content-Type is application/json224 * req.is('json');225 * req.is('application/json');226 * req.is('application/*');227 * // => true228 *229 * req.is('html');230 * // => false231 *232 * @param {String} type233 * @return {Boolean}234 * @api public235 */236refactor req.is and req.accepts*Jonathan Ongbefore adoptioncec0c06
lines 237–239why, one step back237req.is = function(types){238 if (!Array.isArray(types)) types = [].slice.call(arguments);239 return typeis(this, types);refactorTJ Holowaychukbefore adoptionf8a33d1
lines 240–255why, one step back240};241242/**243 * Return the protocol string "http" or "https"244 * when requested with TLS. When the "trust proxy"245 * setting is enabled the "X-Forwarded-Proto" header246 * field will be trusted. If you're running behind247 * a reverse proxy that supplies https for you this248 * may be enabled.249 *250 * @return {String}251 * @api public252 */253254req.__defineGetter__('protocol', function(){255 var trustProxy = this.app.get('trust proxy');add support for multiple X-Forwarded-Proto values. Closes #1646TJ Holowaychukbefore adoption8ab4408
lines 256–259why, one step back256 if (this.connection.encrypted) return 'https';257 if (!trustProxy) return 'http';258 var proto = this.get('X-Forwarded-Proto') || 'http';259 return proto.split(/\s*,\s*/)[0];refactorTJ Holowaychukbefore adoptionf8a33d1
lines 260–321why, one step back260});261262/**263 * Short-hand for:264 *265 * req.protocol == 'https'266 *267 * @return {Boolean}268 * @api public269 */270271req.__defineGetter__('secure', function(){272 return 'https' == this.protocol;273});274275/**276 * Return the remote address, or when277 * "trust proxy" is `true` return278 * the upstream addr.279 *280 * @return {String}281 * @api public282 */283284req.__defineGetter__('ip', function(){285 return this.ips[0] || this.connection.remoteAddress;286});287288/**289 * When "trust proxy" is `true`, parse290 * the "X-Forwarded-For" ip address list.291 *292 * For example if the value were "client, proxy1, proxy2"293 * you would receive the array `["client", "proxy1", "proxy2"]`294 * where "proxy2" is the furthest down-stream.295 *296 * @return {Array}297 * @api public298 */299300req.__defineGetter__('ips', function(){301 var trustProxy = this.app.get('trust proxy');302 var val = this.get('X-Forwarded-For');303 return trustProxy && val304 ? val.split(/ *, */)305 : [];306});307308/**309 * Return basic auth credentials.310 *311 * Examples:312 *313 * // http://tobi:hello@example.com314 * req.auth315 * // => { username: 'tobi', password: 'hello' }316 *317 * @return {Object} or undefined318 * @api public319 */320321req.__defineGetter__('auth', function(){refactor to use basic-authJonathan Ongbefore adoption3cf7b2e
lines 322–328why, one step back322 var auth = basicAuth(this);323 if (auth) {324 // aliases for backwards compatibilty325 auth.username = auth.name;326 auth.password = auth.pass;327 }328 return auth;refactorTJ Holowaychukbefore adoptionf8a33d1
lines 329–347why, one step back329});330331/**332 * Return subdomains as an array.333 *334 * Subdomains are the dot-separated parts of the host before the main domain of335 * the app. By default, the domain of the app is assumed to be the last two336 * parts of the host. This can be changed by setting "subdomain offset".337 *338 * For example, if the domain is "tobi.ferrets.example.com":339 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.340 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.341 *342 * @return {Array}343 * @api public344 */345346req.__defineGetter__('subdomains', function(){347 var offset = this.app.get('subdomain offset');fix `req.subdomains` when no Host is presentTJ Holowaychukbefore adoption8559c0e
line 348why, one step back348 return (this.host || '')refactorTJ Holowaychukbefore adoptionf8a33d1
lines 349–375why, one step back349 .split('.')350 .reverse()351 .slice(offset);352});353354/**355 * Short-hand for `url.parse(req.url).pathname`.356 *357 * @return {String}358 * @api public359 */360361req.__defineGetter__('path', function(){362 return parse(this).pathname;363});364365/**366 * Parse the "Host" header field hostname.367 *368 * @return {String}369 * @api public370 */371372req.__defineGetter__('host', function(){373 var trustProxy = this.app.get('trust proxy');374 var host = trustProxy && this.get('X-Forwarded-Host');375 host = host || this.get('Host');fix `req.host` when no Host is present, return undefinedTJ Holowaychukbefore adoption06ead58
line 376why, one step back376 if (!host) return;refactorTJ Holowaychukbefore adoptionf8a33d1
lines 377–427why, one step back377 return host.split(':')[0];378});379380/**381 * Check if the request is fresh, aka382 * Last-Modified and/or the ETag383 * still match.384 *385 * @return {Boolean}386 * @api public387 */388389req.__defineGetter__('fresh', function(){390 var method = this.method;391 var s = this.res.statusCode;392393 // GET or HEAD for weak freshness validation only394 if ('GET' != method && 'HEAD' != method) return false;395396 // 2xx or 304 as per rfc2616 14.26397 if ((s >= 200 && s < 300) || 304 == s) {398 return fresh(this.headers, this.res._headers);399 }400401 return false;402});403404/**405 * Check if the request is stale, aka406 * "Last-Modified" and / or the "ETag" for the407 * resource has changed.408 *409 * @return {Boolean}410 * @api public411 */412413req.__defineGetter__('stale', function(){414 return !this.fresh;415});416417/**418 * Check if the request was an _XMLHttpRequest_.419 *420 * @return {Boolean}421 * @api public422 */423424req.__defineGetter__('xhr', function(){425 var val = this.get('X-Requested-With') || '';426 return 'xmlhttprequest' == val.toLowerCase();427});