request.js
This file
Path
lib/request.js
426 lines · 9.7 KiB · JavaScript
Last changed by
Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
History of this fileTake it
1/**2 * Module dependencies.3 */45var accepts = require('accepts');6var typeis = require('type-is');7var http = require('http');8var fresh = require('fresh');9var parseRange = require('range-parser');10var parse = require('parseurl');11var proxyaddr = require('proxy-addr');1213/**14 * Request prototype.15 */1617var req = exports = module.exports = {18 __proto__: http.IncomingMessage.prototype19};2021/**22 * Return request header.23 *24 * The `Referrer` header field is special-cased,25 * both `Referrer` and `Referer` are interchangeable.26 *27 * Examples:28 *29 * req.get('Content-Type');30 * // => "text/plain"31 *32 * req.get('content-type');33 * // => "text/plain"34 *35 * req.get('Something');36 * // => undefined37 *38 * Aliased as `req.header()`.39 *40 * @param {String} name41 * @return {String}42 * @api public43 */4445req.get =46req.header = function(name){47 switch (name = name.toLowerCase()) {48 case 'referer':49 case 'referrer':50 return this.headers.referrer51 || this.headers.referer;52 default:53 return this.headers[name];54 }55};5657/**58 * To do: update docs.59 *60 * Check if the given `type(s)` is acceptable, returning61 * the best match when true, otherwise `undefined`, in which62 * case you should respond with 406 "Not Acceptable".63 *64 * The `type` value may be a single mime type string65 * such as "application/json", the extension name66 * such as "json", a comma-delimted list such as "json, html, text/plain",67 * an argument list such as `"json", "html", "text/plain"`,68 * or an array `["json", "html", "text/plain"]`. When a list69 * or array is given the _best_ match, if any is returned.70 *71 * Examples:72 *73 * // Accept: text/html74 * req.accepts('html');75 * // => "html"76 *77 * // Accept: text/*, application/json78 * req.accepts('html');79 * // => "html"80 * req.accepts('text/html');81 * // => "text/html"82 * req.accepts('json, text');83 * // => "json"84 * req.accepts('application/json');85 * // => "application/json"86 *87 * // Accept: text/*, application/json88 * req.accepts('image/png');89 * req.accepts('png');90 * // => undefined91 *92 * // Accept: text/*;q=.5, application/json93 * req.accepts(['html', 'json']);94 * req.accepts('html', 'json');95 * req.accepts('html, json');96 * // => "json"97 *98 * @param {String|Array} type(s)99 * @return {String}100 * @api public101 */102103req.accepts = function(){104 var accept = accepts(this);105 return accept.types.apply(accept, arguments);106};107108/**109 * Check if the given `encoding` is accepted.110 *111 * @param {String} encoding112 * @return {Boolean}113 * @api public114 */115116req.acceptsEncoding = // backwards compatibility117req.acceptsEncodings = function(){118 var accept = accepts(this);119 return accept.encodings.apply(accept, arguments);120};121122/**123 * To do: update docs.124 *125 * Check if the given `charset` is acceptable,126 * otherwise you should respond with 406 "Not Acceptable".127 *128 * @param {String} charset129 * @return {Boolean}130 * @api public131 */132133req.acceptsCharset = // backwards compatibility134req.acceptsCharsets = function(){135 var accept = accepts(this);136 return accept.charsets.apply(accept, arguments);137};138139/**140 * To do: update docs.141 *142 * Check if the given `lang` is acceptable,143 * otherwise you should respond with 406 "Not Acceptable".144 *145 * @param {String} lang146 * @return {Boolean}147 * @api public148 */149150req.acceptsLanguage = // backwards compatibility151req.acceptsLanguages = function(){152 var accept = accepts(this);153 return accept.languages.apply(accept, arguments);154};155156/**157 * Parse Range header field,158 * capping to the given `size`.159 *160 * Unspecified ranges such as "0-" require161 * knowledge of your resource length. In162 * the case of a byte range this is of course163 * the total number of bytes. If the Range164 * header field is not given `null` is returned,165 * `-1` when unsatisfiable, `-2` when syntactically invalid.166 *167 * NOTE: remember that ranges are inclusive, so168 * for example "Range: users=0-3" should respond169 * with 4 users when available, not 3.170 *171 * @param {Number} size172 * @return {Array}173 * @api public174 */175176req.range = function(size){177 var range = this.get('Range');178 if (!range) return;179 return parseRange(size, range);180};181182/**183 * Return the value of param `name` when present or `defaultValue`.184 *185 * - Checks route placeholders, ex: _/user/:id_186 * - Checks body params, ex: id=12, {"id":12}187 * - Checks query string params, ex: ?id=12188 *189 * To utilize request bodies, `req.body`190 * should be an object. This can be done by using191 * the `bodyParser()` middleware.192 *193 * @param {String} name194 * @param {Mixed} [defaultValue]195 * @return {String}196 * @api public197 */198199req.param = function(name, defaultValue){200 var params = this.params || {};201 var body = this.body || {};202 var query = this.query || {};203 if (null != params[name] && params.hasOwnProperty(name)) return params[name];204 if (null != body[name]) return body[name];205 if (null != query[name]) return query[name];206 return defaultValue;207};208209/**210 * Check if the incoming request contains the "Content-Type"211 * header field, and it contains the give mime `type`.212 *213 * Examples:214 *215 * // With Content-Type: text/html; charset=utf-8216 * req.is('html');217 * req.is('text/html');218 * req.is('text/*');219 * // => true220 *221 * // When Content-Type is application/json222 * req.is('json');223 * req.is('application/json');224 * req.is('application/*');225 * // => true226 *227 * req.is('html');228 * // => false229 *230 * @param {String} type231 * @return {Boolean}232 * @api public233 */234235req.is = function(types){236 if (!Array.isArray(types)) types = [].slice.call(arguments);237 return typeis(this, types);238};239240/**241 * Return the protocol string "http" or "https"242 * when requested with TLS. When the "trust proxy"243 * setting trusts the socket address, the244 * "X-Forwarded-Proto" header field will be trusted.245 * If you're running behind a reverse proxy that246 * supplies https for you this may be enabled.247 *248 * @return {String}249 * @api public250 */251252req.__defineGetter__('protocol', function(){253 var trust = this.app.get('trust proxy fn');254255 if (!trust(this.connection.remoteAddress)) {256 return this.connection.encrypted257 ? 'https'258 : 'http';259 }260261 // Note: X-Forwarded-Proto is normally only ever a262 // single value, but this is to be safe.263 var proto = this.get('X-Forwarded-Proto') || 'http';264 return proto.split(/\s*,\s*/)[0];265});266267/**268 * Short-hand for:269 *270 * req.protocol == 'https'271 *272 * @return {Boolean}273 * @api public274 */275276req.__defineGetter__('secure', function(){277 return 'https' == this.protocol;278});279280/**281 * Return the remote address from the trusted proxy.282 *283 * The is the remote address on the socket unless284 * "trust proxy" is set.285 *286 * @return {String}287 * @api public288 */289290req.__defineGetter__('ip', function(){291 var trust = this.app.get('trust proxy fn');292 return proxyaddr(this, trust);293});294295/**296 * When "trust proxy" is set, trusted proxy addresses + client.297 *298 * For example if the value were "client, proxy1, proxy2"299 * you would receive the array `["client", "proxy1", "proxy2"]`300 * where "proxy2" is the furthest down-stream and "proxy1" and301 * "proxy2" were trusted.302 *303 * @return {Array}304 * @api public305 */306307req.__defineGetter__('ips', function(){308 var trust = this.app.get('trust proxy fn');309 var addrs = proxyaddr.all(this, trust);310 return addrs.slice(1).reverse();311});312313/**314 * Return subdomains as an array.315 *316 * Subdomains are the dot-separated parts of the host before the main domain of317 * the app. By default, the domain of the app is assumed to be the last two318 * parts of the host. This can be changed by setting "subdomain offset".319 *320 * For example, if the domain is "tobi.ferrets.example.com":321 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.322 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.323 *324 * @return {Array}325 * @api public326 */327328req.__defineGetter__('subdomains', function(){329 var offset = this.app.get('subdomain offset');330 return (this.host || '')331 .split('.')332 .reverse()333 .slice(offset);334});335336/**337 * Short-hand for `url.parse(req.url).pathname`.338 *339 * @return {String}340 * @api public341 */342343req.__defineGetter__('path', function(){344 return parse(this).pathname;345});346347/**348 * Parse the "Host" header field hostname.349 *350 * When the "trust proxy" setting trusts the socket351 * address, the "X-Forwarded-Host" header field will352 * be trusted.353 *354 * @return {String}355 * @api public356 */357358req.__defineGetter__('host', function(){359 var trust = this.app.get('trust proxy fn');360 var host = this.get('X-Forwarded-Host');361362 if (!host || !trust(this.connection.remoteAddress)) {363 host = this.get('Host');364 }365366 if (!host) return;367368 // IPv6 literal support369 var offset = host[0] === '['370 ? host.indexOf(']') + 1371 : 0;372 var index = host.indexOf(':', offset);373374 return ~index375 ? host.substring(0, index)376 : host;377});378379/**380 * Check if the request is fresh, aka381 * Last-Modified and/or the ETag382 * still match.383 *384 * @return {Boolean}385 * @api public386 */387388req.__defineGetter__('fresh', function(){389 var method = this.method;390 var s = this.res.statusCode;391392 // GET or HEAD for weak freshness validation only393 if ('GET' != method && 'HEAD' != method) return false;394395 // 2xx or 304 as per rfc2616 14.26396 if ((s >= 200 && s < 300) || 304 == s) {397 return fresh(this.headers, this.res._headers);398 }399400 return false;401});402403/**404 * Check if the request is stale, aka405 * "Last-Modified" and / or the "ETag" for the406 * resource has changed.407 *408 * @return {Boolean}409 * @api public410 */411412req.__defineGetter__('stale', function(){413 return !this.fresh;414});415416/**417 * Check if the request was an _XMLHttpRequest_.418 *419 * @return {Boolean}420 * @api public421 */422423req.__defineGetter__('xhr', function(){424 var val = this.get('X-Requested-With') || '';425 return 'xmlhttprequest' == val.toLowerCase();426});