request.js
This file
Path
lib/request.js
415 lines · 8.8 KiB · JavaScript
Last changed by
reverse req.ips arrayTJ Holowaychukbefore adoption54c3d5c
History of this fileTake it
12/*!3 * Express - request4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var http = require('http')13 , utils = require('./utils')14 , connect = require('connect')15 , parse = require('url').parse16 , mime = require('mime');1718/**19 * Request prototype.20 */2122var req = exports = module.exports = {23 __proto__: http.IncomingMessage.prototype24};2526/**27 * Return request header.28 *29 * The `Referrer` header field is special-cased,30 * both `Referrer` and `Referer` will yield are31 * interchangeable.32 *33 * Examples:34 *35 * req.get('Content-Type');36 * // => "text/plain"37 * 38 * req.get('content-type');39 * // => "text/plain"40 * 41 * req.get('Something');42 * // => undefined43 * 44 * @param {String} name45 * @return {String} 46 * @api public47 */4849req.get = function(name){50 switch (name = name.toLowerCase()) {51 case 'referer':52 case 'referrer':53 return this.headers.referrer54 || this.headers.referer;55 default:56 return this.headers[name];57 }58};5960/**61 * Check if the given `type(s)` is acceptable, returning62 * the best match when true, otherwise `undefined`, in which63 * case you should respond with 406 "Not Acceptable".64 *65 * The `type` value may be a single mime type string66 * such as "application/json", the extension name67 * such as "json", a comma-delimted 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 * // => "json"96 *97 * @param {String|Array} type(s)98 * @return {String}99 * @api public100 */101102req.accepts = function(type){103 return utils.accepts(type, this.get('Accept'));104};105106/**107 * Check if the given `charset` is acceptable,108 * otherwise you should respond with 406 "Not Acceptable".109 *110 * @param {String} charset111 * @return {Boolean}112 * @api public113 */114115req.acceptsCharset = function(charset){116 var accepted = this.acceptedCharsets;117 return accepted.length118 ? ~accepted.indexOf(charset)119 : true;120};121122/**123 * Check if the given `lang` is acceptable,124 * otherwise you should respond with 406 "Not Acceptable".125 *126 * @param {String} lang127 * @return {Boolean}128 * @api public129 */130131req.acceptsLanguage = function(lang){132 var accepted = this.acceptedLanguages;133 return accepted.length134 ? ~accepted.indexOf(lang)135 : true;136};137138/**139 * Return an array of Accepted media types140 * ordered from highest quality to lowest.141 *142 * Examples:143 *144 * [ { value: 'application/json',145 * quality: 1,146 * type: 'application',147 * subtype: 'json' },148 * { value: 'text/html',149 * quality: 0.5,150 * type: 'text',151 * subtype: 'html' } ]152 *153 * @return {Array}154 * @api public155 */156157req.__defineGetter__('accepted', function(){158 var accept = this.get('Accept');159 return accept160 ? utils.parseAccept(accept)161 : [];162});163164/**165 * Return an array of Accepted languages166 * ordered from highest quality to lowest.167 *168 * Examples:169 *170 * Accept-Language: en;q=.5, en-us171 * ['en-us', 'en']172 *173 * @return {Array}174 * @api public175 */176177req.__defineGetter__('acceptedLanguages', function(){178 var accept = this.get('Accept-Language');179 return accept180 ? utils181 .parseQuality(accept)182 .map(function(obj){183 return obj.value;184 })185 : [];186});187188/**189 * Return an array of Accepted charsets190 * ordered from highest quality to lowest.191 *192 * Examples:193 *194 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8195 * ['unicode-1-1', 'iso-8859-5']196 *197 * @return {Array}198 * @api public199 */200201req.__defineGetter__('acceptedCharsets', function(){202 var accept = this.get('Accept-Charset');203 return accept204 ? utils205 .parseQuality(accept)206 .map(function(obj){207 return obj.value;208 })209 : [];210});211212/**213 * Return the value of param `name` when present or `defaultValue`.214 *215 * - Checks body params, ex: id=12, {"id":12}216 * - Checks route placeholders, ex: _/user/:id_217 * - Checks query string params, ex: ?id=12218 *219 * To utilize request bodies, `req.body`220 * should be an object. This can be done by using221 * the `connect.bodyParser()` middleware.222 *223 * @param {String} name224 * @param {Mixed} defaultValue225 * @return {String}226 * @api public227 */228229req.param = function(name, defaultValue){230 // req.body231 if (this.body && undefined !== this.body[name]) return this.body[name];232233 // route params234 if (this.params235 && this.params.hasOwnProperty(name)236 && undefined !== this.params[name]) {237 return this.params[name]; 238 }239240 // query-string241 if (undefined !== this.query[name]) return this.query[name]; 242243 return defaultValue;244};245246/**247 * Check if the incoming request contains the "Content-Type" 248 * header field, and it contains the give mime `type`.249 *250 * Examples:251 *252 * // With Content-Type: text/html; charset=utf-8253 * req.is('html');254 * req.is('text/html');255 * req.is('text/*');256 * // => true257 * 258 * // When Content-Type is application/json259 * req.is('json');260 * req.is('application/json');261 * req.is('application/*');262 * // => true263 * 264 * req.is('html');265 * // => false266 * 267 * Now within our route callbacks, we can use to to assert content types268 * such as "image/jpeg", "image/png", etc.269 * 270 * app.post('/image/upload', function(req, res, next){271 * if (req.is('image/*')) {272 * // do something273 * } else {274 * next();275 * }276 * });277 * 278 * @param {String} type279 * @return {Boolean}280 * @api public281 */282283req.is = function(type){284 var ct = this.get('Content-Type');285 if (!ct) return false;286 ct = ct.split(';')[0];287 if (!~type.indexOf('/')) type = mime.lookup(type);288 if (~type.indexOf('*')) {289 type = type.split('/');290 ct = ct.split('/');291 if ('*' == type[0] && type[1] == ct[1]) return true;292 if ('*' == type[1] && type[0] == ct[0]) return true;293 return false;294 }295 return !! ~ct.indexOf(type);296};297298/**299 * Return the protocol string "http" or "https"300 * when requested with TLS. When the "trust proxy" 301 * setting is enabled the "X-Forwarded-Proto" header302 * field will be trusted. If you're running behind303 * a reverse proxy that supplies https for you this304 * may be enabled.305 *306 * @return {String}307 * @api public308 */309310req.__defineGetter__('protocol', function(trustProxy){311 var trustProxy = this.app.settings['trust proxy'];312 return this.connection.encrypted313 ? 'https'314 : trustProxy315 ? (this.get('X-Forwarded-Proto') || 'http')316 : 'http';317});318319/**320 * Short-hand for:321 *322 * req.protocol == 'https'323 *324 * @return {Boolean}325 * @api public326 */327328req.__defineGetter__('secure', function(){329 return 'https' == this.protocol;330});331332/**333 * When "trust proxy" is `true`, parse334 * the "X-Forwarded-For" ip address list.335 *336 * For example if the value were "client, proxy1, proxy2"337 * you would receive the array `["proxy2", "proxy1", "client"]`338 * where "proxy2" is the furthest down-stream.339 *340 * @return {Array}341 * @api public342 */343344req.__defineGetter__('ips', function(){345 var val = this.get('X-Forwarded-For');346 return val347 ? val.split(/ *, */).reverse()348 : [];349});350351/**352 * Return subdomains as an array.353 *354 * For example "tobi.ferrets.example.com"355 * would provide `["ferrets", "tobi"]`.356 *357 * @return {Array}358 * @api public359 */360361req.__defineGetter__('subdomains', function(){362 return this.get('Host')363 .split('.')364 .slice(0, -2)365 .reverse();366});367368/**369 * Short-hand for `require('url').parse(req.url).pathname`.370 *371 * @return {String}372 * @api public373 */374375req.__defineGetter__('path', function(){376 return parse(this.url).pathname;377});378379/**380 * Check if the request is fresh, aka381 * Last-Modified and/or the ETag382 * still match.383 *384 * @return {Boolean}385 * @api public386 */387388req.__defineGetter__('fresh', function(){389 return ! this.stale;390});391392/**393 * Check if the request is stale, aka394 * "Last-Modified" and / or the "ETag" for the395 * resource has changed.396 *397 * @return {Boolean}398 * @api public399 */400401req.__defineGetter__('stale', function(){402 return connect.utils.modified(this, this.res);403});404405/**406 * Check if the request was an _XMLHttpRequest_.407 *408 * @return {Boolean}409 * @api public410 */411412req.__defineGetter__('xhr', function(){413 var val = this.get('X-Requested-With') || '';414 return 'xmlhttprequest' == val.toLowerCase();415});