request.js
This file
Path
lib/request.js
479 lines · 10.3 KiB · JavaScript
Last changed by
Remove req.param()Douglas Christopher Wilsonbefore adoption21d52da
History of this fileTake it
1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2013 Roman Shtylman5 * Copyright(c) 2014-2015 Douglas Christopher Wilson6 * MIT Licensed7 */89'use strict';1011/**12 * Module dependencies.13 * @private14 */1516var accepts = require('accepts');17var isIP = require('net').isIP;18var typeis = require('type-is');19var http = require('http');20var fresh = require('fresh');21var parseRange = require('range-parser');22var parse = require('parseurl');23var proxyaddr = require('proxy-addr');2425/**26 * Request prototype.27 */2829var req = exports = module.exports = {30 __proto__: http.IncomingMessage.prototype31};3233/**34 * Return request header.35 *36 * The `Referrer` header field is special-cased,37 * both `Referrer` and `Referer` are interchangeable.38 *39 * Examples:40 *41 * req.get('Content-Type');42 * // => "text/plain"43 *44 * req.get('content-type');45 * // => "text/plain"46 *47 * req.get('Something');48 * // => undefined49 *50 * Aliased as `req.header()`.51 *52 * @param {String} name53 * @return {String}54 * @public55 */5657req.get =58req.header = function header(name) {59 var lc = name.toLowerCase();6061 switch (lc) {62 case 'referer':63 case 'referrer':64 return this.headers.referrer65 || this.headers.referer;66 default:67 return this.headers[lc];68 }69};7071/**72 * To do: update docs.73 *74 * Check if the given `type(s)` is acceptable, returning75 * the best match when true, otherwise `undefined`, in which76 * case you should respond with 406 "Not Acceptable".77 *78 * The `type` value may be a single MIME type string79 * such as "application/json", an extension name80 * such as "json", a comma-delimited list such as "json, html, text/plain",81 * an argument list such as `"json", "html", "text/plain"`,82 * or an array `["json", "html", "text/plain"]`. When a list83 * or array is given, the _best_ match, if any is returned.84 *85 * Examples:86 *87 * // Accept: text/html88 * req.accepts('html');89 * // => "html"90 *91 * // Accept: text/*, application/json92 * req.accepts('html');93 * // => "html"94 * req.accepts('text/html');95 * // => "text/html"96 * req.accepts('json, text');97 * // => "json"98 * req.accepts('application/json');99 * // => "application/json"100 *101 * // Accept: text/*, application/json102 * req.accepts('image/png');103 * req.accepts('png');104 * // => undefined105 *106 * // Accept: text/*;q=.5, application/json107 * req.accepts(['html', 'json']);108 * req.accepts('html', 'json');109 * req.accepts('html, json');110 * // => "json"111 *112 * @param {String|Array} type(s)113 * @return {String|Array|Boolean}114 * @public115 */116117req.accepts = function(){118 var accept = accepts(this);119 return accept.types.apply(accept, arguments);120};121122/**123 * Check if the given `encoding`s are accepted.124 *125 * @param {String} ...encoding126 * @return {String|Array}127 * @public128 */129130req.acceptsEncodings = function(){131 var accept = accepts(this);132 return accept.encodings.apply(accept, arguments);133};134135/**136 * Check if the given `charset`s are acceptable,137 * otherwise you should respond with 406 "Not Acceptable".138 *139 * @param {String} ...charset140 * @return {String|Array}141 * @public142 */143144req.acceptsCharsets = function(){145 var accept = accepts(this);146 return accept.charsets.apply(accept, arguments);147};148149/**150 * Check if the given `lang`s are acceptable,151 * otherwise you should respond with 406 "Not Acceptable".152 *153 * @param {String} ...lang154 * @return {String|Array}155 * @public156 */157158req.acceptsLanguages = function(){159 var accept = accepts(this);160 return accept.languages.apply(accept, arguments);161};162163/**164 * Parse Range header field,165 * capping to the given `size`.166 *167 * Unspecified ranges such as "0-" require168 * knowledge of your resource length. In169 * the case of a byte range this is of course170 * the total number of bytes. If the Range171 * header field is not given `null` is returned,172 * `-1` when unsatisfiable, `-2` when syntactically invalid.173 *174 * NOTE: remember that ranges are inclusive, so175 * for example "Range: users=0-3" should respond176 * with 4 users when available, not 3.177 *178 * @param {Number} size179 * @return {Array}180 * @public181 */182183req.range = function(size){184 var range = this.get('Range');185 if (!range) return;186 return parseRange(size, range);187};188189/**190 * Parse the query string of `req.url`.191 *192 * This uses the "query parser" setting to parse the raw193 * string into an object.194 *195 * @return {String}196 * @api public197 */198199defineGetter(req, 'query', function query(){200 var queryparse = this.app.get('query parser fn');201202 if (!queryparse) {203 // parsing is disabled204 return Object.create(null);205 }206207 var querystring = parse(this).query;208209 return queryparse(querystring);210});211212/**213 * Check if the incoming request contains the "Content-Type"214 * header field, and it contains the give mime `type`.215 *216 * Examples:217 *218 * // With Content-Type: text/html; charset=utf-8219 * req.is('html');220 * req.is('text/html');221 * req.is('text/*');222 * // => true223 *224 * // When Content-Type is application/json225 * req.is('json');226 * req.is('application/json');227 * req.is('application/*');228 * // => true229 *230 * req.is('html');231 * // => false232 *233 * @param {String|Array} types...234 * @return {String|false|null}235 * @public236 */237238req.is = function is(types) {239 var arr = types;240241 // support flattened arguments242 if (!Array.isArray(types)) {243 arr = new Array(arguments.length);244 for (var i = 0; i < arr.length; i++) {245 arr[i] = arguments[i];246 }247 }248249 return typeis(this, arr);250};251252/**253 * Return the protocol string "http" or "https"254 * when requested with TLS. When the "trust proxy"255 * setting trusts the socket address, the256 * "X-Forwarded-Proto" header field will be trusted257 * and used if present.258 *259 * If you're running behind a reverse proxy that260 * supplies https for you this may be enabled.261 *262 * @return {String}263 * @public264 */265266defineGetter(req, 'protocol', function protocol(){267 var proto = this.connection.encrypted268 ? 'https'269 : 'http';270 var trust = this.app.get('trust proxy fn');271272 if (!trust(this.connection.remoteAddress, 0)) {273 return proto;274 }275276 // Note: X-Forwarded-Proto is normally only ever a277 // single value, but this is to be safe.278 proto = this.get('X-Forwarded-Proto') || proto;279 return proto.split(/\s*,\s*/)[0];280});281282/**283 * Short-hand for:284 *285 * req.protocol == 'https'286 *287 * @return {Boolean}288 * @public289 */290291defineGetter(req, 'secure', function secure(){292 return this.protocol === 'https';293});294295/**296 * Return the remote address from the trusted proxy.297 *298 * The is the remote address on the socket unless299 * "trust proxy" is set.300 *301 * @return {String}302 * @public303 */304305defineGetter(req, 'ip', function ip(){306 var trust = this.app.get('trust proxy fn');307 return proxyaddr(this, trust);308});309310/**311 * When "trust proxy" is set, trusted proxy addresses + client.312 *313 * For example if the value were "client, proxy1, proxy2"314 * you would receive the array `["client", "proxy1", "proxy2"]`315 * where "proxy2" is the furthest down-stream and "proxy1" and316 * "proxy2" were trusted.317 *318 * @return {Array}319 * @public320 */321322defineGetter(req, 'ips', function ips() {323 var trust = this.app.get('trust proxy fn');324 var addrs = proxyaddr.all(this, trust);325 return addrs.slice(1).reverse();326});327328/**329 * Return subdomains as an array.330 *331 * Subdomains are the dot-separated parts of the host before the main domain of332 * the app. By default, the domain of the app is assumed to be the last two333 * parts of the host. This can be changed by setting "subdomain offset".334 *335 * For example, if the domain is "tobi.ferrets.example.com":336 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.337 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.338 *339 * @return {Array}340 * @public341 */342343defineGetter(req, 'subdomains', function subdomains() {344 var hostname = this.hostname;345346 if (!hostname) return [];347348 var offset = this.app.get('subdomain offset');349 var subdomains = !isIP(hostname)350 ? hostname.split('.').reverse()351 : [hostname];352353 return subdomains.slice(offset);354});355356/**357 * Short-hand for `url.parse(req.url).pathname`.358 *359 * @return {String}360 * @public361 */362363defineGetter(req, 'path', function path() {364 return parse(this).pathname;365});366367/**368 * Parse the "Host" header field to a host.369 *370 * When the "trust proxy" setting trusts the socket371 * address, the "X-Forwarded-Host" header field will372 * be trusted.373 *374 * @return {String}375 * @public376 */377378defineGetter(req, 'host', function host(){379 var trust = this.app.get('trust proxy fn');380 var val = this.get('X-Forwarded-Host');381382 if (!val || !trust(this.connection.remoteAddress, 0)) {383 val = this.get('Host');384 }385386 return val || undefined;387});388389/**390 * Parse the "Host" header field to a hostname.391 *392 * When the "trust proxy" setting trusts the socket393 * address, the "X-Forwarded-Host" header field will394 * be trusted.395 *396 * @return {String}397 * @api public398 */399400defineGetter(req, 'hostname', function hostname(){401 var host = this.host;402403 if (!host) return;404405 // IPv6 literal support406 var offset = host[0] === '['407 ? host.indexOf(']') + 1408 : 0;409 var index = host.indexOf(':', offset);410411 return index !== -1412 ? host.substring(0, index)413 : host;414});415416/**417 * Check if the request is fresh, aka418 * Last-Modified and/or the ETag419 * still match.420 *421 * @return {Boolean}422 * @public423 */424425defineGetter(req, 'fresh', function(){426 var method = this.method;427 var s = this.res.statusCode;428429 // GET or HEAD for weak freshness validation only430 if ('GET' != method && 'HEAD' != method) return false;431432 // 2xx or 304 as per rfc2616 14.26433 if ((s >= 200 && s < 300) || 304 == s) {434 return fresh(this.headers, (this.res._headers || {}));435 }436437 return false;438});439440/**441 * Check if the request is stale, aka442 * "Last-Modified" and / or the "ETag" for the443 * resource has changed.444 *445 * @return {Boolean}446 * @public447 */448449defineGetter(req, 'stale', function stale(){450 return !this.fresh;451});452453/**454 * Check if the request was an _XMLHttpRequest_.455 *456 * @return {Boolean}457 * @public458 */459460defineGetter(req, 'xhr', function xhr(){461 var val = this.get('X-Requested-With') || '';462 return val.toLowerCase() === 'xmlhttprequest';463});464465/**466 * Helper function for creating a getter on an object.467 *468 * @param {Object} obj469 * @param {String} name470 * @param {Function} getter471 * @private472 */473function defineGetter(obj, name, getter) {474 Object.defineProperty(obj, name, {475 configurable: true,476 enumerable: true,477 get: getter478 });479};