Skip to content
Myr

request.js

This file

Path

lib/request.js

526 lines · 11.4 KiB · JavaScript

Last changed by

add req.acceptsEncoding(name)TJ Holowaychukbefore adoption2e53cb7

History of this file

Take it

12/**3 * Module dependencies.4 */56var http = require('http')7  , utils = require('./utils')8  , connect = require('connect')9  , fresh = require('fresh')10  , parseRange = require('range-parser')11  , parse = connect.utils.parseUrl12  , mime = connect.mime;1314/**15 * Request prototype.16 */1718var req = exports = module.exports = {19  __proto__: http.IncomingMessage.prototype20};2122/**23 * Return request header.24 *25 * The `Referrer` header field is special-cased,26 * both `Referrer` and `Referer` are interchangeable.27 *28 * Examples:29 *30 *     req.get('Content-Type');31 *     // => "text/plain"32 *33 *     req.get('content-type');34 *     // => "text/plain"35 *36 *     req.get('Something');37 *     // => undefined38 *39 * Aliased as `req.header()`.40 *41 * @param {String} name42 * @return {String}43 * @api public44 */4546req.get =47req.header = function(name){48  switch (name = name.toLowerCase()) {49    case 'referer':50    case 'referrer':51      return this.headers.referrer52        || this.headers.referer;53    default:54      return this.headers[name];55  }56};5758/**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 * or an array `["json", "html", "text/plain"]`. When a list67 * or array is given the _best_ match, if any is returned.68 *69 * Examples:70 *71 *     // Accept: text/html72 *     req.accepts('html');73 *     // => "html"74 *75 *     // Accept: text/*, application/json76 *     req.accepts('html');77 *     // => "html"78 *     req.accepts('text/html');79 *     // => "text/html"80 *     req.accepts('json, text');81 *     // => "json"82 *     req.accepts('application/json');83 *     // => "application/json"84 *85 *     // Accept: text/*, application/json86 *     req.accepts('image/png');87 *     req.accepts('png');88 *     // => undefined89 *90 *     // Accept: text/*;q=.5, application/json91 *     req.accepts(['html', 'json']);92 *     req.accepts('html, json');93 *     // => "json"94 *95 * @param {String|Array} type(s)96 * @return {String}97 * @api public98 */99100req.accepts = function(type){101  return utils.accepts(type, this.get('Accept'));102};103104/**105 * Check if the given `encoding` is accepted.106 *107 * @param {String} encoding108 * @return {Boolean}109 * @api public110 */111112req.acceptsEncoding = function(encoding){113  return ~this.acceptedEncodings.indexOf(encoding);114};115116/**117 * Check if the given `charset` is acceptable,118 * otherwise you should respond with 406 "Not Acceptable".119 *120 * @param {String} charset121 * @return {Boolean}122 * @api public123 */124125req.acceptsCharset = function(charset){126  var accepted = this.acceptedCharsets;127  return accepted.length128    ? ~accepted.indexOf(charset)129    : true;130};131132/**133 * Check if the given `lang` is acceptable,134 * otherwise you should respond with 406 "Not Acceptable".135 *136 * @param {String} lang137 * @return {Boolean}138 * @api public139 */140141req.acceptsLanguage = function(lang){142  var accepted = this.acceptedLanguages;143  return accepted.length144    ? ~accepted.indexOf(lang)145    : true;146};147148/**149 * Parse Range header field,150 * capping to the given `size`.151 *152 * Unspecified ranges such as "0-" require153 * knowledge of your resource length. In154 * the case of a byte range this is of course155 * the total number of bytes. If the Range156 * header field is not given `null` is returned,157 * `-1` when unsatisfiable, `-2` when syntactically invalid.158 *159 * NOTE: remember that ranges are inclusive, so160 * for example "Range: users=0-3" should respond161 * with 4 users when available, not 3.162 *163 * @param {Number} size164 * @return {Array}165 * @api public166 */167168req.range = function(size){169  var range = this.get('Range');170  if (!range) return;171  return parseRange(size, range);172};173174/**175 * Return an array of encodings.176 *177 * Examples:178 *179 *     ['gzip', 'deflate']180 *181 * @return {Array}182 * @api public183 */184185req.__defineGetter__('acceptedEncodings', function(){186  var accept = this.get('Accept-Encoding');187  return accept188    ? accept.trim().split(/ *, */)189    : [];190});191192/**193 * Return an array of Accepted media types194 * ordered from highest quality to lowest.195 *196 * Examples:197 *198 *     [ { value: 'application/json',199 *         quality: 1,200 *         type: 'application',201 *         subtype: 'json' },202 *       { value: 'text/html',203 *         quality: 0.5,204 *         type: 'text',205 *         subtype: 'html' } ]206 *207 * @return {Array}208 * @api public209 */210211req.__defineGetter__('accepted', function(){212  var accept = this.get('Accept');213  return accept214    ? utils.parseAccept(accept)215    : [];216});217218/**219 * Return an array of Accepted languages220 * ordered from highest quality to lowest.221 *222 * Examples:223 *224 *     Accept-Language: en;q=.5, en-us225 *     ['en-us', 'en']226 *227 * @return {Array}228 * @api public229 */230231req.__defineGetter__('acceptedLanguages', function(){232  var accept = this.get('Accept-Language');233  return accept234    ? utils235      .parseParams(accept)236      .map(function(obj){237        return obj.value;238      })239    : [];240});241242/**243 * Return an array of Accepted charsets244 * ordered from highest quality to lowest.245 *246 * Examples:247 *248 *     Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8249 *     ['unicode-1-1', 'iso-8859-5']250 *251 * @return {Array}252 * @api public253 */254255req.__defineGetter__('acceptedCharsets', function(){256  var accept = this.get('Accept-Charset');257  return accept258    ? utils259      .parseParams(accept)260      .map(function(obj){261        return obj.value;262      })263    : [];264});265266/**267 * Return the value of param `name` when present or `defaultValue`.268 *269 *  - Checks route placeholders, ex: _/user/:id_270 *  - Checks body params, ex: id=12, {"id":12}271 *  - Checks query string params, ex: ?id=12272 *273 * To utilize request bodies, `req.body`274 * should be an object. This can be done by using275 * the `connect.bodyParser()` middleware.276 *277 * @param {String} name278 * @param {Mixed} [defaultValue]279 * @return {String}280 * @api public281 */282283req.param = function(name, defaultValue){284  var params = this.params || {};285  var body = this.body || {};286  var query = this.query || {};287  if (null != params[name] && params.hasOwnProperty(name)) return params[name];288  if (null != body[name]) return body[name];289  if (null != query[name]) return query[name];290  return defaultValue;291};292293/**294 * Check if the incoming request contains the "Content-Type"295 * header field, and it contains the give mime `type`.296 *297 * Examples:298 *299 *      // With Content-Type: text/html; charset=utf-8300 *      req.is('html');301 *      req.is('text/html');302 *      req.is('text/*');303 *      // => true304 *305 *      // When Content-Type is application/json306 *      req.is('json');307 *      req.is('application/json');308 *      req.is('application/*');309 *      // => true310 *311 *      req.is('html');312 *      // => false313 *314 * @param {String} type315 * @return {Boolean}316 * @api public317 */318319req.is = function(type){320  var ct = this.get('Content-Type');321  if (!ct) return false;322  ct = ct.split(';')[0];323  if (!~type.indexOf('/')) type = mime.lookup(type);324  if (~type.indexOf('*')) {325    type = type.split('/');326    ct = ct.split('/');327    if ('*' == type[0] && type[1] == ct[1]) return true;328    if ('*' == type[1] && type[0] == ct[0]) return true;329    return false;330  }331  return !! ~ct.indexOf(type);332};333334/**335 * Return the protocol string "http" or "https"336 * when requested with TLS. When the "trust proxy"337 * setting is enabled the "X-Forwarded-Proto" header338 * field will be trusted. If you're running behind339 * a reverse proxy that supplies https for you this340 * may be enabled.341 *342 * @return {String}343 * @api public344 */345346req.__defineGetter__('protocol', function(){347  var trustProxy = this.app.get('trust proxy');348  return this.connection.encrypted349    ? 'https'350    : trustProxy351      ? (this.get('X-Forwarded-Proto') || 'http')352      : 'http';353});354355/**356 * Short-hand for:357 *358 *    req.protocol == 'https'359 *360 * @return {Boolean}361 * @api public362 */363364req.__defineGetter__('secure', function(){365  return 'https' == this.protocol;366});367368/**369 * Return the remote address, or when370 * "trust proxy" is `true` return371 * the upstream addr.372 *373 * @return {String}374 * @api public375 */376377req.__defineGetter__('ip', function(){378  return this.ips[0] || this.connection.remoteAddress;379});380381/**382 * When "trust proxy" is `true`, parse383 * the "X-Forwarded-For" ip address list.384 *385 * For example if the value were "client, proxy1, proxy2"386 * you would receive the array `["client", "proxy1", "proxy2"]`387 * where "proxy2" is the furthest down-stream.388 *389 * @return {Array}390 * @api public391 */392393req.__defineGetter__('ips', function(){394  var trustProxy = this.app.get('trust proxy');395  var val = this.get('X-Forwarded-For');396  return trustProxy && val397    ? val.split(/ *, */)398    : [];399});400401/**402 * Return basic auth credentials.403 *404 * Examples:405 *406 *    // http://tobi:hello@example.com407 *    req.auth408 *    // => { username: 'tobi', password: 'hello' }409 *410 * @return {Object} or undefined411 * @api public412 */413414req.__defineGetter__('auth', function(){415  // missing416  var auth = this.get('Authorization');417  if (!auth) return;418419  // malformed420  var parts = auth.split(' ');421  if ('basic' != parts[0].toLowerCase()) return;422  if (!parts[1]) return;423  auth = parts[1];424425  // credentials426  auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/);427  if (!auth) return;428  return { username: auth[1], password: auth[2] };429});430431/**432 * Return subdomains as an array.433 *434 * Subdomains are the dot-separated parts of the host before the main domain of435 * the app. By default, the domain of the app is assumed to be the last two436 * parts of the host. This can be changed by setting "subdomain offset".437 *438 * For example, if the domain is "tobi.ferrets.example.com":439 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.440 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.441 *442 * @return {Array}443 * @api public444 */445446req.__defineGetter__('subdomains', function(){447  var offset = this.app.get('subdomain offset');448  return this.get('Host')449    .split('.')450    .reverse()451    .slice(offset);452});453454/**455 * Short-hand for `url.parse(req.url).pathname`.456 *457 * @return {String}458 * @api public459 */460461req.__defineGetter__('path', function(){462  return parse(this).pathname;463});464465/**466 * Parse the "Host" header field hostname.467 *468 * @return {String}469 * @api public470 */471472req.__defineGetter__('host', function(){473  var trustProxy = this.app.get('trust proxy');474  var host = trustProxy && this.get('X-Forwarded-Host');475  host = host || this.get('Host');476  return host.split(':')[0];477});478479/**480 * Check if the request is fresh, aka481 * Last-Modified and/or the ETag482 * still match.483 *484 * @return {Boolean}485 * @api public486 */487488req.__defineGetter__('fresh', function(){489  var method = this.method;490  var s = this.res.statusCode;491492  // GET or HEAD for weak freshness validation only493  if ('GET' != method && 'HEAD' != method) return false;494495  // 2xx or 304 as per rfc2616 14.26496  if ((s >= 200 && s < 300) || 304 == s) {497    return fresh(this.headers, this.res._headers);498  }499500  return false;501});502503/**504 * Check if the request is stale, aka505 * "Last-Modified" and / or the "ETag" for the506 * resource has changed.507 *508 * @return {Boolean}509 * @api public510 */511512req.__defineGetter__('stale', function(){513  return !this.fresh;514});515516/**517 * Check if the request was an _XMLHttpRequest_.518 *519 * @return {Boolean}520 * @api public521 */522523req.__defineGetter__('xhr', function(){524  var val = this.get('X-Requested-With') || '';525  return 'xmlhttprequest' == val.toLowerCase();526});