Skip to content
Myr

request.js

This file

Path

lib/request.js

401 lines · 9.1 KiB · JavaScript

Last changed by

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

History of this file

Take 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');1112/**13 * Request prototype.14 */1516var req = exports = module.exports = {17  __proto__: http.IncomingMessage.prototype18};1920/**21 * Return request header.22 *23 * The `Referrer` header field is special-cased,24 * both `Referrer` and `Referer` are interchangeable.25 *26 * Examples:27 *28 *     req.get('Content-Type');29 *     // => "text/plain"30 *31 *     req.get('content-type');32 *     // => "text/plain"33 *34 *     req.get('Something');35 *     // => undefined36 *37 * Aliased as `req.header()`.38 *39 * @param {String} name40 * @return {String}41 * @api public42 */4344req.get =45req.header = function(name){46  switch (name = name.toLowerCase()) {47    case 'referer':48    case 'referrer':49      return this.headers.referrer50        || this.headers.referer;51    default:52      return this.headers[name];53  }54};5556/**57 * To do: update docs.58 *59 * Check if the given `type(s)` is acceptable, returning60 * the best match when true, otherwise `undefined`, in which61 * case you should respond with 406 "Not Acceptable".62 *63 * The `type` value may be a single mime type string64 * such as "application/json", the extension name65 * such as "json", a comma-delimted list such as "json, html, text/plain",66 * an argument list such as `"json", "html", "text/plain"`,67 * or an array `["json", "html", "text/plain"]`. When a list68 * or array is given the _best_ match, if any is returned.69 *70 * Examples:71 *72 *     // Accept: text/html73 *     req.accepts('html');74 *     // => "html"75 *76 *     // Accept: text/*, application/json77 *     req.accepts('html');78 *     // => "html"79 *     req.accepts('text/html');80 *     // => "text/html"81 *     req.accepts('json, text');82 *     // => "json"83 *     req.accepts('application/json');84 *     // => "application/json"85 *86 *     // Accept: text/*, application/json87 *     req.accepts('image/png');88 *     req.accepts('png');89 *     // => undefined90 *91 *     // Accept: text/*;q=.5, application/json92 *     req.accepts(['html', 'json']);93 *     req.accepts('html', 'json');94 *     req.accepts('html, json');95 *     // => "json"96 *97 * @param {String|Array} type(s)98 * @return {String}99 * @api public100 */101102req.accepts = function(){103  var accept = accepts(this);104  return accept.types.apply(accept, arguments);105};106107/**108 * Check if the given `encoding` is accepted.109 *110 * @param {String} encoding111 * @return {Boolean}112 * @api public113 */114115req.acceptsEncoding = // backwards compatibility116req.acceptsEncodings = function(){117  var accept = accepts(this);118  return accept.encodings.apply(accept, arguments);119};120121/**122 * To do: update docs.123 *124 * Check if the given `charset` is acceptable,125 * otherwise you should respond with 406 "Not Acceptable".126 *127 * @param {String} charset128 * @return {Boolean}129 * @api public130 */131132req.acceptsCharset = // backwards compatibility133req.acceptsCharsets = function(){134  var accept = accepts(this);135  return accept.charsets.apply(accept, arguments);136};137138/**139 * To do: update docs.140 *141 * Check if the given `lang` is acceptable,142 * otherwise you should respond with 406 "Not Acceptable".143 *144 * @param {String} lang145 * @return {Boolean}146 * @api public147 */148149req.acceptsLanguage = // backwards compatibility150req.acceptsLanguages = function(){151  var accept = accepts(this);152  return accept.languages.apply(accept, arguments);153};154155/**156 * Parse Range header field,157 * capping to the given `size`.158 *159 * Unspecified ranges such as "0-" require160 * knowledge of your resource length. In161 * the case of a byte range this is of course162 * the total number of bytes. If the Range163 * header field is not given `null` is returned,164 * `-1` when unsatisfiable, `-2` when syntactically invalid.165 *166 * NOTE: remember that ranges are inclusive, so167 * for example "Range: users=0-3" should respond168 * with 4 users when available, not 3.169 *170 * @param {Number} size171 * @return {Array}172 * @api public173 */174175req.range = function(size){176  var range = this.get('Range');177  if (!range) return;178  return parseRange(size, range);179};180181/**182 * Return the value of param `name` when present or `defaultValue`.183 *184 *  - Checks route placeholders, ex: _/user/:id_185 *  - Checks body params, ex: id=12, {"id":12}186 *  - Checks query string params, ex: ?id=12187 *188 * To utilize request bodies, `req.body`189 * should be an object. This can be done by using190 * the `bodyParser()` middleware.191 *192 * @param {String} name193 * @param {Mixed} [defaultValue]194 * @return {String}195 * @api public196 */197198req.param = function(name, defaultValue){199  var params = this.params || {};200  var body = this.body || {};201  var query = this.query || {};202  if (null != params[name] && params.hasOwnProperty(name)) return params[name];203  if (null != body[name]) return body[name];204  if (null != query[name]) return query[name];205  return defaultValue;206};207208/**209 * Check if the incoming request contains the "Content-Type"210 * header field, and it contains the give mime `type`.211 *212 * Examples:213 *214 *      // With Content-Type: text/html; charset=utf-8215 *      req.is('html');216 *      req.is('text/html');217 *      req.is('text/*');218 *      // => true219 *220 *      // When Content-Type is application/json221 *      req.is('json');222 *      req.is('application/json');223 *      req.is('application/*');224 *      // => true225 *226 *      req.is('html');227 *      // => false228 *229 * @param {String} type230 * @return {Boolean}231 * @api public232 */233234req.is = function(types){235  if (!Array.isArray(types)) types = [].slice.call(arguments);236  return typeis(this, types);237};238239/**240 * Return the protocol string "http" or "https"241 * when requested with TLS. When the "trust proxy"242 * setting is enabled the "X-Forwarded-Proto" header243 * field will be trusted. If you're running behind244 * a reverse proxy that supplies https for you this245 * may be enabled.246 *247 * @return {String}248 * @api public249 */250251req.__defineGetter__('protocol', function(){252  var trustProxy = this.app.get('trust proxy');253  if (this.connection.encrypted) return 'https';254  if (!trustProxy) return 'http';255  var proto = this.get('X-Forwarded-Proto') || 'http';256  return proto.split(/\s*,\s*/)[0];257});258259/**260 * Short-hand for:261 *262 *    req.protocol == 'https'263 *264 * @return {Boolean}265 * @api public266 */267268req.__defineGetter__('secure', function(){269  return 'https' == this.protocol;270});271272/**273 * Return the remote address, or when274 * "trust proxy" is `true` return275 * the upstream addr.276 *277 * @return {String}278 * @api public279 */280281req.__defineGetter__('ip', function(){282  return this.ips[0] || this.connection.remoteAddress;283});284285/**286 * When "trust proxy" is `true`, parse287 * the "X-Forwarded-For" ip address list.288 *289 * For example if the value were "client, proxy1, proxy2"290 * you would receive the array `["client", "proxy1", "proxy2"]`291 * where "proxy2" is the furthest down-stream.292 *293 * @return {Array}294 * @api public295 */296297req.__defineGetter__('ips', function(){298  var trustProxy = this.app.get('trust proxy');299  var val = this.get('X-Forwarded-For');300  return trustProxy && val301    ? val.split(/ *, */)302    : [];303});304305/**306 * Return subdomains as an array.307 *308 * Subdomains are the dot-separated parts of the host before the main domain of309 * the app. By default, the domain of the app is assumed to be the last two310 * parts of the host. This can be changed by setting "subdomain offset".311 *312 * For example, if the domain is "tobi.ferrets.example.com":313 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.314 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.315 *316 * @return {Array}317 * @api public318 */319320req.__defineGetter__('subdomains', function(){321  var offset = this.app.get('subdomain offset');322  return (this.host || '')323    .split('.')324    .reverse()325    .slice(offset);326});327328/**329 * Short-hand for `url.parse(req.url).pathname`.330 *331 * @return {String}332 * @api public333 */334335req.__defineGetter__('path', function(){336  return parse(this).pathname;337});338339/**340 * Parse the "Host" header field hostname.341 *342 * @return {String}343 * @api public344 */345346req.__defineGetter__('host', function(){347  var trustProxy = this.app.get('trust proxy');348  var host = trustProxy && this.get('X-Forwarded-Host');349  host = host || this.get('Host');350  if (!host) return;351  return host.split(':')[0];352});353354/**355 * Check if the request is fresh, aka356 * Last-Modified and/or the ETag357 * still match.358 *359 * @return {Boolean}360 * @api public361 */362363req.__defineGetter__('fresh', function(){364  var method = this.method;365  var s = this.res.statusCode;366367  // GET or HEAD for weak freshness validation only368  if ('GET' != method && 'HEAD' != method) return false;369370  // 2xx or 304 as per rfc2616 14.26371  if ((s >= 200 && s < 300) || 304 == s) {372    return fresh(this.headers, this.res._headers);373  }374375  return false;376});377378/**379 * Check if the request is stale, aka380 * "Last-Modified" and / or the "ETag" for the381 * resource has changed.382 *383 * @return {Boolean}384 * @api public385 */386387req.__defineGetter__('stale', function(){388  return !this.fresh;389});390391/**392 * Check if the request was an _XMLHttpRequest_.393 *394 * @return {Boolean}395 * @api public396 */397398req.__defineGetter__('xhr', function(){399  var val = this.get('X-Requested-With') || '';400  return 'xmlhttprequest' == val.toLowerCase();401});