request.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. /*!
  2. * express
  3. * Copyright(c) 2009-2013 TJ Holowaychuk
  4. * Copyright(c) 2013 Roman Shtylman
  5. * Copyright(c) 2014-2015 Douglas Christopher Wilson
  6. * MIT Licensed
  7. */
  8. 'use strict';
  9. /**
  10. * Module dependencies.
  11. * @private
  12. */
  13. var accepts = require('accepts');
  14. var deprecate = require('depd')('express');
  15. var isIP = require('net').isIP;
  16. var typeis = require('type-is');
  17. var http = require('http');
  18. var fresh = require('fresh');
  19. var parseRange = require('range-parser');
  20. var parse = require('parseurl');
  21. var proxyaddr = require('proxy-addr');
  22. /**
  23. * Request prototype.
  24. */
  25. var req = exports = module.exports = {
  26. __proto__: http.IncomingMessage.prototype
  27. };
  28. /**
  29. * Return request header.
  30. *
  31. * The `Referrer` header field is special-cased,
  32. * both `Referrer` and `Referer` are interchangeable.
  33. *
  34. * Examples:
  35. *
  36. * req.get('Content-Type');
  37. * // => "text/plain"
  38. *
  39. * req.get('content-type');
  40. * // => "text/plain"
  41. *
  42. * req.get('Something');
  43. * // => undefined
  44. *
  45. * Aliased as `req.header()`.
  46. *
  47. * @param {String} name
  48. * @return {String}
  49. * @public
  50. */
  51. req.get =
  52. req.header = function header(name) {
  53. var lc = name.toLowerCase();
  54. switch (lc) {
  55. case 'referer':
  56. case 'referrer':
  57. return this.headers.referrer
  58. || this.headers.referer;
  59. default:
  60. return this.headers[lc];
  61. }
  62. };
  63. /**
  64. * To do: update docs.
  65. *
  66. * Check if the given `type(s)` is acceptable, returning
  67. * the best match when true, otherwise `undefined`, in which
  68. * case you should respond with 406 "Not Acceptable".
  69. *
  70. * The `type` value may be a single MIME type string
  71. * such as "application/json", an extension name
  72. * such as "json", a comma-delimited list such as "json, html, text/plain",
  73. * an argument list such as `"json", "html", "text/plain"`,
  74. * or an array `["json", "html", "text/plain"]`. When a list
  75. * or array is given, the _best_ match, if any is returned.
  76. *
  77. * Examples:
  78. *
  79. * // Accept: text/html
  80. * req.accepts('html');
  81. * // => "html"
  82. *
  83. * // Accept: text/*, application/json
  84. * req.accepts('html');
  85. * // => "html"
  86. * req.accepts('text/html');
  87. * // => "text/html"
  88. * req.accepts('json, text');
  89. * // => "json"
  90. * req.accepts('application/json');
  91. * // => "application/json"
  92. *
  93. * // Accept: text/*, application/json
  94. * req.accepts('image/png');
  95. * req.accepts('png');
  96. * // => undefined
  97. *
  98. * // Accept: text/*;q=.5, application/json
  99. * req.accepts(['html', 'json']);
  100. * req.accepts('html', 'json');
  101. * req.accepts('html, json');
  102. * // => "json"
  103. *
  104. * @param {String|Array} type(s)
  105. * @return {String|Array|Boolean}
  106. * @public
  107. */
  108. req.accepts = function(){
  109. var accept = accepts(this);
  110. return accept.types.apply(accept, arguments);
  111. };
  112. /**
  113. * Check if the given `encoding`s are accepted.
  114. *
  115. * @param {String} ...encoding
  116. * @return {String|Array}
  117. * @public
  118. */
  119. req.acceptsEncodings = function(){
  120. var accept = accepts(this);
  121. return accept.encodings.apply(accept, arguments);
  122. };
  123. req.acceptsEncoding = deprecate.function(req.acceptsEncodings,
  124. 'req.acceptsEncoding: Use acceptsEncodings instead');
  125. /**
  126. * Check if the given `charset`s are acceptable,
  127. * otherwise you should respond with 406 "Not Acceptable".
  128. *
  129. * @param {String} ...charset
  130. * @return {String|Array}
  131. * @public
  132. */
  133. req.acceptsCharsets = function(){
  134. var accept = accepts(this);
  135. return accept.charsets.apply(accept, arguments);
  136. };
  137. req.acceptsCharset = deprecate.function(req.acceptsCharsets,
  138. 'req.acceptsCharset: Use acceptsCharsets instead');
  139. /**
  140. * Check if the given `lang`s are acceptable,
  141. * otherwise you should respond with 406 "Not Acceptable".
  142. *
  143. * @param {String} ...lang
  144. * @return {String|Array}
  145. * @public
  146. */
  147. req.acceptsLanguages = function(){
  148. var accept = accepts(this);
  149. return accept.languages.apply(accept, arguments);
  150. };
  151. req.acceptsLanguage = deprecate.function(req.acceptsLanguages,
  152. 'req.acceptsLanguage: Use acceptsLanguages instead');
  153. /**
  154. * Parse Range header field,
  155. * capping to the given `size`.
  156. *
  157. * Unspecified ranges such as "0-" require
  158. * knowledge of your resource length. In
  159. * the case of a byte range this is of course
  160. * the total number of bytes. If the Range
  161. * header field is not given `null` is returned,
  162. * `-1` when unsatisfiable, `-2` when syntactically invalid.
  163. *
  164. * NOTE: remember that ranges are inclusive, so
  165. * for example "Range: users=0-3" should respond
  166. * with 4 users when available, not 3.
  167. *
  168. * @param {Number} size
  169. * @return {Array}
  170. * @public
  171. */
  172. req.range = function(size){
  173. var range = this.get('Range');
  174. if (!range) return;
  175. return parseRange(size, range);
  176. };
  177. /**
  178. * Return the value of param `name` when present or `defaultValue`.
  179. *
  180. * - Checks route placeholders, ex: _/user/:id_
  181. * - Checks body params, ex: id=12, {"id":12}
  182. * - Checks query string params, ex: ?id=12
  183. *
  184. * To utilize request bodies, `req.body`
  185. * should be an object. This can be done by using
  186. * the `bodyParser()` middleware.
  187. *
  188. * @param {String} name
  189. * @param {Mixed} [defaultValue]
  190. * @return {String}
  191. * @public
  192. */
  193. req.param = function param(name, defaultValue) {
  194. var params = this.params || {};
  195. var body = this.body || {};
  196. var query = this.query || {};
  197. var args = arguments.length === 1
  198. ? 'name'
  199. : 'name, default';
  200. deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead');
  201. if (null != params[name] && params.hasOwnProperty(name)) return params[name];
  202. if (null != body[name]) return body[name];
  203. if (null != query[name]) return query[name];
  204. return defaultValue;
  205. };
  206. /**
  207. * Check if the incoming request contains the "Content-Type"
  208. * header field, and it contains the give mime `type`.
  209. *
  210. * Examples:
  211. *
  212. * // With Content-Type: text/html; charset=utf-8
  213. * req.is('html');
  214. * req.is('text/html');
  215. * req.is('text/*');
  216. * // => true
  217. *
  218. * // When Content-Type is application/json
  219. * req.is('json');
  220. * req.is('application/json');
  221. * req.is('application/*');
  222. * // => true
  223. *
  224. * req.is('html');
  225. * // => false
  226. *
  227. * @param {String|Array} types...
  228. * @return {String|false|null}
  229. * @public
  230. */
  231. req.is = function is(types) {
  232. var arr = types;
  233. // support flattened arguments
  234. if (!Array.isArray(types)) {
  235. arr = new Array(arguments.length);
  236. for (var i = 0; i < arr.length; i++) {
  237. arr[i] = arguments[i];
  238. }
  239. }
  240. return typeis(this, arr);
  241. };
  242. /**
  243. * Return the protocol string "http" or "https"
  244. * when requested with TLS. When the "trust proxy"
  245. * setting trusts the socket address, the
  246. * "X-Forwarded-Proto" header field will be trusted
  247. * and used if present.
  248. *
  249. * If you're running behind a reverse proxy that
  250. * supplies https for you this may be enabled.
  251. *
  252. * @return {String}
  253. * @public
  254. */
  255. defineGetter(req, 'protocol', function protocol(){
  256. var proto = this.connection.encrypted
  257. ? 'https'
  258. : 'http';
  259. var trust = this.app.get('trust proxy fn');
  260. if (!trust(this.connection.remoteAddress, 0)) {
  261. return proto;
  262. }
  263. // Note: X-Forwarded-Proto is normally only ever a
  264. // single value, but this is to be safe.
  265. proto = this.get('X-Forwarded-Proto') || proto;
  266. return proto.split(/\s*,\s*/)[0];
  267. });
  268. /**
  269. * Short-hand for:
  270. *
  271. * req.protocol == 'https'
  272. *
  273. * @return {Boolean}
  274. * @public
  275. */
  276. defineGetter(req, 'secure', function secure(){
  277. return this.protocol === 'https';
  278. });
  279. /**
  280. * Return the remote address from the trusted proxy.
  281. *
  282. * The is the remote address on the socket unless
  283. * "trust proxy" is set.
  284. *
  285. * @return {String}
  286. * @public
  287. */
  288. defineGetter(req, 'ip', function ip(){
  289. var trust = this.app.get('trust proxy fn');
  290. return proxyaddr(this, trust);
  291. });
  292. /**
  293. * When "trust proxy" is set, trusted proxy addresses + client.
  294. *
  295. * For example if the value were "client, proxy1, proxy2"
  296. * you would receive the array `["client", "proxy1", "proxy2"]`
  297. * where "proxy2" is the furthest down-stream and "proxy1" and
  298. * "proxy2" were trusted.
  299. *
  300. * @return {Array}
  301. * @public
  302. */
  303. defineGetter(req, 'ips', function ips() {
  304. var trust = this.app.get('trust proxy fn');
  305. var addrs = proxyaddr.all(this, trust);
  306. return addrs.slice(1).reverse();
  307. });
  308. /**
  309. * Return subdomains as an array.
  310. *
  311. * Subdomains are the dot-separated parts of the host before the main domain of
  312. * the app. By default, the domain of the app is assumed to be the last two
  313. * parts of the host. This can be changed by setting "subdomain offset".
  314. *
  315. * For example, if the domain is "tobi.ferrets.example.com":
  316. * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
  317. * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
  318. *
  319. * @return {Array}
  320. * @public
  321. */
  322. defineGetter(req, 'subdomains', function subdomains() {
  323. var hostname = this.hostname;
  324. if (!hostname) return [];
  325. var offset = this.app.get('subdomain offset');
  326. var subdomains = !isIP(hostname)
  327. ? hostname.split('.').reverse()
  328. : [hostname];
  329. return subdomains.slice(offset);
  330. });
  331. /**
  332. * Short-hand for `url.parse(req.url).pathname`.
  333. *
  334. * @return {String}
  335. * @public
  336. */
  337. defineGetter(req, 'path', function path() {
  338. return parse(this).pathname;
  339. });
  340. /**
  341. * Parse the "Host" header field to a hostname.
  342. *
  343. * When the "trust proxy" setting trusts the socket
  344. * address, the "X-Forwarded-Host" header field will
  345. * be trusted.
  346. *
  347. * @return {String}
  348. * @public
  349. */
  350. defineGetter(req, 'hostname', function hostname(){
  351. var trust = this.app.get('trust proxy fn');
  352. var host = this.get('X-Forwarded-Host');
  353. if (!host || !trust(this.connection.remoteAddress, 0)) {
  354. host = this.get('Host');
  355. }
  356. if (!host) return;
  357. // IPv6 literal support
  358. var offset = host[0] === '['
  359. ? host.indexOf(']') + 1
  360. : 0;
  361. var index = host.indexOf(':', offset);
  362. return index !== -1
  363. ? host.substring(0, index)
  364. : host;
  365. });
  366. // TODO: change req.host to return host in next major
  367. defineGetter(req, 'host', deprecate.function(function host(){
  368. return this.hostname;
  369. }, 'req.host: Use req.hostname instead'));
  370. /**
  371. * Check if the request is fresh, aka
  372. * Last-Modified and/or the ETag
  373. * still match.
  374. *
  375. * @return {Boolean}
  376. * @public
  377. */
  378. defineGetter(req, 'fresh', function(){
  379. var method = this.method;
  380. var s = this.res.statusCode;
  381. // GET or HEAD for weak freshness validation only
  382. if ('GET' != method && 'HEAD' != method) return false;
  383. // 2xx or 304 as per rfc2616 14.26
  384. if ((s >= 200 && s < 300) || 304 == s) {
  385. return fresh(this.headers, (this.res._headers || {}));
  386. }
  387. return false;
  388. });
  389. /**
  390. * Check if the request is stale, aka
  391. * "Last-Modified" and / or the "ETag" for the
  392. * resource has changed.
  393. *
  394. * @return {Boolean}
  395. * @public
  396. */
  397. defineGetter(req, 'stale', function stale(){
  398. return !this.fresh;
  399. });
  400. /**
  401. * Check if the request was an _XMLHttpRequest_.
  402. *
  403. * @return {Boolean}
  404. * @public
  405. */
  406. defineGetter(req, 'xhr', function xhr(){
  407. var val = this.get('X-Requested-With') || '';
  408. return val.toLowerCase() === 'xmlhttprequest';
  409. });
  410. /**
  411. * Helper function for creating a getter on an object.
  412. *
  413. * @param {Object} obj
  414. * @param {String} name
  415. * @param {Function} getter
  416. * @private
  417. */
  418. function defineGetter(obj, name, getter) {
  419. Object.defineProperty(obj, name, {
  420. configurable: true,
  421. enumerable: true,
  422. get: getter
  423. });
  424. };