request.js
This file
Path
lib/request.js
430 lines · 9.0 KiB · JavaScript
Last changed by
GET / HEAD only for req.freshTJ Holowaychukbefore adoptionc10223b
History of this fileTake it
12/**3 * Module dependencies.4 */56var http = require('http')7 , utils = require('./utils')8 , connect = require('connect')9 , fresh = require('fresh')10 , parse = connect.utils.parseUrl11 , mime = connect.mime;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 * Check if the given `type(s)` is acceptable, returning59 * the best match when true, otherwise `undefined`, in which60 * case you should respond with 406 "Not Acceptable".61 *62 * The `type` value may be a single mime type string63 * such as "application/json", the extension name64 * such as "json", a comma-delimted list such as "json, html, text/plain",65 * or an array `["json", "html", "text/plain"]`. When a list66 * or array is given the _best_ match, if any is returned.67 *68 * Examples:69 * 70 * // Accept: text/html71 * req.accepts('html');72 * // => "html"73 *74 * // Accept: text/*, application/json75 * req.accepts('html');76 * // => "html"77 * req.accepts('text/html');78 * // => "text/html"79 * req.accepts('json, text');80 * // => "json"81 * req.accepts('application/json');82 * // => "application/json"83 *84 * // Accept: text/*, application/json85 * req.accepts('image/png');86 * req.accepts('png');87 * // => undefined88 *89 * // Accept: text/*;q=.5, application/json90 * req.accepts(['html', 'json']);91 * req.accepts('html, json');92 * // => "json"93 *94 * @param {String|Array} type(s)95 * @return {String}96 * @api public97 */9899req.accepts = function(type){100 return utils.accepts(type, this.get('Accept'));101};102103/**104 * Check if the given `charset` is acceptable,105 * otherwise you should respond with 406 "Not Acceptable".106 *107 * @param {String} charset108 * @return {Boolean}109 * @api public110 */111112req.acceptsCharset = function(charset){113 var accepted = this.acceptedCharsets;114 return accepted.length115 ? ~accepted.indexOf(charset)116 : true;117};118119/**120 * Check if the given `lang` is acceptable,121 * otherwise you should respond with 406 "Not Acceptable".122 *123 * @param {String} lang124 * @return {Boolean}125 * @api public126 */127128req.acceptsLanguage = function(lang){129 var accepted = this.acceptedLanguages;130 return accepted.length131 ? ~accepted.indexOf(lang)132 : true;133};134135/**136 * Return an array of Accepted media types137 * ordered from highest quality to lowest.138 *139 * Examples:140 *141 * [ { value: 'application/json',142 * quality: 1,143 * type: 'application',144 * subtype: 'json' },145 * { value: 'text/html',146 * quality: 0.5,147 * type: 'text',148 * subtype: 'html' } ]149 *150 * @return {Array}151 * @api public152 */153154req.__defineGetter__('accepted', function(){155 var accept = this.get('Accept');156 return accept157 ? utils.parseAccept(accept)158 : [];159});160161/**162 * Return an array of Accepted languages163 * ordered from highest quality to lowest.164 *165 * Examples:166 *167 * Accept-Language: en;q=.5, en-us168 * ['en-us', 'en']169 *170 * @return {Array}171 * @api public172 */173174req.__defineGetter__('acceptedLanguages', function(){175 var accept = this.get('Accept-Language');176 return accept177 ? utils178 .parseQuality(accept)179 .map(function(obj){180 return obj.value;181 })182 : [];183});184185/**186 * Return an array of Accepted charsets187 * ordered from highest quality to lowest.188 *189 * Examples:190 *191 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8192 * ['unicode-1-1', 'iso-8859-5']193 *194 * @return {Array}195 * @api public196 */197198req.__defineGetter__('acceptedCharsets', function(){199 var accept = this.get('Accept-Charset');200 return accept201 ? utils202 .parseQuality(accept)203 .map(function(obj){204 return obj.value;205 })206 : [];207});208209/**210 * Return the value of param `name` when present or `defaultValue`.211 *212 * - Checks route placeholders, ex: _/user/:id_213 * - Checks body params, ex: id=12, {"id":12}214 * - Checks query string params, ex: ?id=12215 *216 * To utilize request bodies, `req.body`217 * should be an object. This can be done by using218 * the `connect.bodyParser()` middleware.219 *220 * @param {String} name221 * @param {Mixed} defaultValue222 * @return {String}223 * @api public224 */225226req.param = function(name, defaultValue){227 var params = this.params || {};228 var body = this.body || {};229 var query = this.query || {};230 if (null != params[name] && params.hasOwnProperty(name)) return params[name];231 if (null != body[name]) return body[name];232 if (null != query[name]) return query[name];233 return defaultValue;234};235236/**237 * Check if the incoming request contains the "Content-Type" 238 * header field, and it contains the give mime `type`.239 *240 * Examples:241 *242 * // With Content-Type: text/html; charset=utf-8243 * req.is('html');244 * req.is('text/html');245 * req.is('text/*');246 * // => true247 * 248 * // When Content-Type is application/json249 * req.is('json');250 * req.is('application/json');251 * req.is('application/*');252 * // => true253 * 254 * req.is('html');255 * // => false256 * 257 * @param {String} type258 * @return {Boolean}259 * @api public260 */261262req.is = function(type){263 var ct = this.get('Content-Type');264 if (!ct) return false;265 ct = ct.split(';')[0];266 if (!~type.indexOf('/')) type = mime.lookup(type);267 if (~type.indexOf('*')) {268 type = type.split('/');269 ct = ct.split('/');270 if ('*' == type[0] && type[1] == ct[1]) return true;271 if ('*' == type[1] && type[0] == ct[0]) return true;272 return false;273 }274 return !! ~ct.indexOf(type);275};276277/**278 * Return the protocol string "http" or "https"279 * when requested with TLS. When the "trust proxy" 280 * setting is enabled the "X-Forwarded-Proto" header281 * field will be trusted. If you're running behind282 * a reverse proxy that supplies https for you this283 * may be enabled.284 *285 * @return {String}286 * @api public287 */288289req.__defineGetter__('protocol', function(){290 var trustProxy = this.app.get('trust proxy');291 return this.connection.encrypted292 ? 'https'293 : trustProxy294 ? (this.get('X-Forwarded-Proto') || 'http')295 : 'http';296});297298/**299 * Short-hand for:300 *301 * req.protocol == 'https'302 *303 * @return {Boolean}304 * @api public305 */306307req.__defineGetter__('secure', function(){308 return 'https' == this.protocol;309});310311/**312 * Return the remote address, or when313 * "trust proxy" is `true` return314 * the upstream addr.315 *316 * @return {String}317 * @api public318 */319320req.__defineGetter__('ip', function(){321 return this.ips[0] || this.connection.remoteAddress;322});323324/**325 * When "trust proxy" is `true`, parse326 * the "X-Forwarded-For" ip address list.327 *328 * For example if the value were "client, proxy1, proxy2"329 * you would receive the array `["client", "proxy1", "proxy2"]`330 * where "proxy2" is the furthest down-stream.331 *332 * @return {Array}333 * @api public334 */335336req.__defineGetter__('ips', function(){337 var trustProxy = this.app.get('trust proxy');338 var val = this.get('X-Forwarded-For');339 return trustProxy && val340 ? val.split(/ *, */)341 : [];342});343344/**345 * Return subdomains as an array.346 *347 * For example "tobi.ferrets.example.com"348 * would provide `["ferrets", "tobi"]`.349 *350 * @return {Array}351 * @api public352 */353354req.__defineGetter__('subdomains', function(){355 return this.get('Host')356 .split('.')357 .slice(0, -2)358 .reverse();359});360361/**362 * Short-hand for `url.parse(req.url).pathname`.363 *364 * @return {String}365 * @api public366 */367368req.__defineGetter__('path', function(){369 return parse(this).pathname;370});371372/**373 * Parse the "Host" header field hostname.374 *375 * @return {String}376 * @api public377 */378379req.__defineGetter__('host', function(){380 return this.get('Host').split(':')[0];381});382383/**384 * Check if the request is fresh, aka385 * Last-Modified and/or the ETag386 * still match.387 *388 * @return {Boolean}389 * @api public390 */391392req.__defineGetter__('fresh', function(){393 var method = this.method;394 var s = this.res.statusCode;395396 // GET or HEAD for weak freshness validation only397 if ('GET' != method && 'HEAD' != method) return false;398399 // 2xx or 304 as per rfc2616 14.26400 if ((s >= 200 && s < 300) || 304 == s) {401 return fresh(this.headers, this.res._headers);402 }403404 return false;405});406407/**408 * Check if the request is stale, aka409 * "Last-Modified" and / or the "ETag" for the410 * resource has changed.411 *412 * @return {Boolean}413 * @api public414 */415416req.__defineGetter__('stale', function(){417 return !this.fresh;418});419420/**421 * Check if the request was an _XMLHttpRequest_.422 *423 * @return {Boolean}424 * @api public425 */426427req.__defineGetter__('xhr', function(){428 var val = this.get('X-Requested-With') || '';429 return 'xmlhttprequest' == val.toLowerCase();430});