request.js
This file
Path
lib/request.js
402 lines · 9.1 KiB · JavaScript
Last changed by
remove req.authJonathan Ongbefore adoption68996d7
History of this fileTake it
12/**3 * Module dependencies.4 */56var accepts = require('accepts');7var typeis = require('type-is');8var http = require('http');9var fresh = require('fresh');10var parseRange = require('range-parser');11var parse = require('parseurl');1213/**14 * Request prototype.15 */1617var req = exports = module.exports = {18 __proto__: http.IncomingMessage.prototype19};2021/**22 * Return request header.23 *24 * The `Referrer` header field is special-cased,25 * both `Referrer` and `Referer` are interchangeable.26 *27 * Examples:28 *29 * req.get('Content-Type');30 * // => "text/plain"31 *32 * req.get('content-type');33 * // => "text/plain"34 *35 * req.get('Something');36 * // => undefined37 *38 * Aliased as `req.header()`.39 *40 * @param {String} name41 * @return {String}42 * @api public43 */4445req.get =46req.header = function(name){47 switch (name = name.toLowerCase()) {48 case 'referer':49 case 'referrer':50 return this.headers.referrer51 || this.headers.referer;52 default:53 return this.headers[name];54 }55};5657/**58 * To do: update docs.59 *60 * Check if the given `type(s)` is acceptable, returning61 * the best match when true, otherwise `undefined`, in which62 * case you should respond with 406 "Not Acceptable".63 *64 * The `type` value may be a single mime type string65 * such as "application/json", the extension name66 * such as "json", a comma-delimted list such as "json, html, text/plain",67 * an argument list such as `"json", "html", "text/plain"`,68 * or an array `["json", "html", "text/plain"]`. When a list69 * or array is given the _best_ match, if any is returned.70 *71 * Examples:72 *73 * // Accept: text/html74 * req.accepts('html');75 * // => "html"76 *77 * // Accept: text/*, application/json78 * req.accepts('html');79 * // => "html"80 * req.accepts('text/html');81 * // => "text/html"82 * req.accepts('json, text');83 * // => "json"84 * req.accepts('application/json');85 * // => "application/json"86 *87 * // Accept: text/*, application/json88 * req.accepts('image/png');89 * req.accepts('png');90 * // => undefined91 *92 * // Accept: text/*;q=.5, application/json93 * req.accepts(['html', 'json']);94 * req.accepts('html', 'json');95 * req.accepts('html, json');96 * // => "json"97 *98 * @param {String|Array} type(s)99 * @return {String}100 * @api public101 */102103req.accepts = function(){104 var accept = accepts(this);105 return accept.types.apply(accept, arguments);106};107108/**109 * Check if the given `encoding` is accepted.110 *111 * @param {String} encoding112 * @return {Boolean}113 * @api public114 */115116req.acceptsEncoding = // backwards compatibility117req.acceptsEncodings = function(){118 var accept = accepts(this);119 return accept.encodings.apply(accept, arguments);120};121122/**123 * To do: update docs.124 *125 * Check if the given `charset` is acceptable,126 * otherwise you should respond with 406 "Not Acceptable".127 *128 * @param {String} charset129 * @return {Boolean}130 * @api public131 */132133req.acceptsCharset = // backwards compatibility134req.acceptsCharsets = function(){135 var accept = accepts(this);136 return accept.charsets.apply(accept, arguments);137};138139/**140 * To do: update docs.141 *142 * Check if the given `lang` is acceptable,143 * otherwise you should respond with 406 "Not Acceptable".144 *145 * @param {String} lang146 * @return {Boolean}147 * @api public148 */149150req.acceptsLanguage = // backwards compatibility151req.acceptsLanguages = function(){152 var accept = accepts(this);153 return accept.languages.apply(accept, arguments);154};155156/**157 * Parse Range header field,158 * capping to the given `size`.159 *160 * Unspecified ranges such as "0-" require161 * knowledge of your resource length. In162 * the case of a byte range this is of course163 * the total number of bytes. If the Range164 * header field is not given `null` is returned,165 * `-1` when unsatisfiable, `-2` when syntactically invalid.166 *167 * NOTE: remember that ranges are inclusive, so168 * for example "Range: users=0-3" should respond169 * with 4 users when available, not 3.170 *171 * @param {Number} size172 * @return {Array}173 * @api public174 */175176req.range = function(size){177 var range = this.get('Range');178 if (!range) return;179 return parseRange(size, range);180};181182/**183 * Return the value of param `name` when present or `defaultValue`.184 *185 * - Checks route placeholders, ex: _/user/:id_186 * - Checks body params, ex: id=12, {"id":12}187 * - Checks query string params, ex: ?id=12188 *189 * To utilize request bodies, `req.body`190 * should be an object. This can be done by using191 * the `bodyParser()` middleware.192 *193 * @param {String} name194 * @param {Mixed} [defaultValue]195 * @return {String}196 * @api public197 */198199req.param = function(name, defaultValue){200 var params = this.params || {};201 var body = this.body || {};202 var query = this.query || {};203 if (null != params[name] && params.hasOwnProperty(name)) return params[name];204 if (null != body[name]) return body[name];205 if (null != query[name]) return query[name];206 return defaultValue;207};208209/**210 * Check if the incoming request contains the "Content-Type"211 * header field, and it contains the give mime `type`.212 *213 * Examples:214 *215 * // With Content-Type: text/html; charset=utf-8216 * req.is('html');217 * req.is('text/html');218 * req.is('text/*');219 * // => true220 *221 * // When Content-Type is application/json222 * req.is('json');223 * req.is('application/json');224 * req.is('application/*');225 * // => true226 *227 * req.is('html');228 * // => false229 *230 * @param {String} type231 * @return {Boolean}232 * @api public233 */234235req.is = function(types){236 if (!Array.isArray(types)) types = [].slice.call(arguments);237 return typeis(this, types);238};239240/**241 * Return the protocol string "http" or "https"242 * when requested with TLS. When the "trust proxy"243 * setting is enabled the "X-Forwarded-Proto" header244 * field will be trusted. If you're running behind245 * a reverse proxy that supplies https for you this246 * may be enabled.247 *248 * @return {String}249 * @api public250 */251252req.__defineGetter__('protocol', function(){253 var trustProxy = this.app.get('trust proxy');254 if (this.connection.encrypted) return 'https';255 if (!trustProxy) return 'http';256 var proto = this.get('X-Forwarded-Proto') || 'http';257 return proto.split(/\s*,\s*/)[0];258});259260/**261 * Short-hand for:262 *263 * req.protocol == 'https'264 *265 * @return {Boolean}266 * @api public267 */268269req.__defineGetter__('secure', function(){270 return 'https' == this.protocol;271});272273/**274 * Return the remote address, or when275 * "trust proxy" is `true` return276 * the upstream addr.277 *278 * @return {String}279 * @api public280 */281282req.__defineGetter__('ip', function(){283 return this.ips[0] || this.connection.remoteAddress;284});285286/**287 * When "trust proxy" is `true`, parse288 * the "X-Forwarded-For" ip address list.289 *290 * For example if the value were "client, proxy1, proxy2"291 * you would receive the array `["client", "proxy1", "proxy2"]`292 * where "proxy2" is the furthest down-stream.293 *294 * @return {Array}295 * @api public296 */297298req.__defineGetter__('ips', function(){299 var trustProxy = this.app.get('trust proxy');300 var val = this.get('X-Forwarded-For');301 return trustProxy && val302 ? val.split(/ *, */)303 : [];304});305306/**307 * Return subdomains as an array.308 *309 * Subdomains are the dot-separated parts of the host before the main domain of310 * the app. By default, the domain of the app is assumed to be the last two311 * parts of the host. This can be changed by setting "subdomain offset".312 *313 * For example, if the domain is "tobi.ferrets.example.com":314 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.315 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.316 *317 * @return {Array}318 * @api public319 */320321req.__defineGetter__('subdomains', function(){322 var offset = this.app.get('subdomain offset');323 return (this.host || '')324 .split('.')325 .reverse()326 .slice(offset);327});328329/**330 * Short-hand for `url.parse(req.url).pathname`.331 *332 * @return {String}333 * @api public334 */335336req.__defineGetter__('path', function(){337 return parse(this).pathname;338});339340/**341 * Parse the "Host" header field hostname.342 *343 * @return {String}344 * @api public345 */346347req.__defineGetter__('host', function(){348 var trustProxy = this.app.get('trust proxy');349 var host = trustProxy && this.get('X-Forwarded-Host');350 host = host || this.get('Host');351 if (!host) return;352 return host.split(':')[0];353});354355/**356 * Check if the request is fresh, aka357 * Last-Modified and/or the ETag358 * still match.359 *360 * @return {Boolean}361 * @api public362 */363364req.__defineGetter__('fresh', function(){365 var method = this.method;366 var s = this.res.statusCode;367368 // GET or HEAD for weak freshness validation only369 if ('GET' != method && 'HEAD' != method) return false;370371 // 2xx or 304 as per rfc2616 14.26372 if ((s >= 200 && s < 300) || 304 == s) {373 return fresh(this.headers, this.res._headers);374 }375376 return false;377});378379/**380 * Check if the request is stale, aka381 * "Last-Modified" and / or the "ETag" for the382 * resource has changed.383 *384 * @return {Boolean}385 * @api public386 */387388req.__defineGetter__('stale', function(){389 return !this.fresh;390});391392/**393 * Check if the request was an _XMLHttpRequest_.394 *395 * @return {Boolean}396 * @api public397 */398399req.__defineGetter__('xhr', function(){400 var val = this.get('X-Requested-With') || '';401 return 'xmlhttprequest' == val.toLowerCase();402});