request.js 9.7 KB

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