request.js
This file
Path
lib/request.js
418 lines · 8.8 KiB · JavaScript
Last changed by
docsTJ Holowaychukbefore adoption27b1b5e
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 * Aliased as `req.header()`.45 *46 * @param {String} name47 * @return {String} 48 * @api public49 */5051req.get = 52req.header = function(name){53 switch (name = name.toLowerCase()) {54 case 'referer':55 case 'referrer':56 return this.headers.referrer57 || this.headers.referer;58 default:59 return this.headers[name];60 }61};6263/**64 * Check if the given `type(s)` is acceptable, returning65 * the best match when true, otherwise `undefined`, in which66 * case you should respond with 406 "Not Acceptable".67 *68 * The `type` value may be a single mime type string69 * such as "application/json", the extension name70 * such as "json", a comma-delimted list such as "json, html, text/plain",71 * or an array `["json", "html", "text/plain"]`. When a list72 * or array is given the _best_ match, if any is returned.73 *74 * Examples:75 * 76 * // Accept: text/html77 * req.accepts('html');78 * // => "html"79 *80 * // Accept: text/*, application/json81 * req.accepts('html');82 * // => "html"83 * req.accepts('text/html');84 * // => "text/html"85 * req.accepts('json, text');86 * // => "json"87 * req.accepts('application/json');88 * // => "application/json"89 *90 * // Accept: text/*, application/json91 * req.accepts('image/png');92 * req.accepts('png');93 * // => undefined94 *95 * // Accept: text/*;q=.5, application/json96 * req.accepts(['html', 'json']);97 * req.accepts('html, json');98 * // => "json"99 *100 * @param {String|Array} type(s)101 * @return {String}102 * @api public103 */104105req.accepts = function(type){106 return utils.accepts(type, this.get('Accept'));107};108109/**110 * Check if the given `charset` is acceptable,111 * otherwise you should respond with 406 "Not Acceptable".112 *113 * @param {String} charset114 * @return {Boolean}115 * @api public116 */117118req.acceptsCharset = function(charset){119 var accepted = this.acceptedCharsets;120 return accepted.length121 ? ~accepted.indexOf(charset)122 : true;123};124125/**126 * Check if the given `lang` is acceptable,127 * otherwise you should respond with 406 "Not Acceptable".128 *129 * @param {String} lang130 * @return {Boolean}131 * @api public132 */133134req.acceptsLanguage = function(lang){135 var accepted = this.acceptedLanguages;136 return accepted.length137 ? ~accepted.indexOf(lang)138 : true;139};140141/**142 * Return an array of Accepted media types143 * ordered from highest quality to lowest.144 *145 * Examples:146 *147 * [ { value: 'application/json',148 * quality: 1,149 * type: 'application',150 * subtype: 'json' },151 * { value: 'text/html',152 * quality: 0.5,153 * type: 'text',154 * subtype: 'html' } ]155 *156 * @return {Array}157 * @api public158 */159160req.__defineGetter__('accepted', function(){161 var accept = this.get('Accept');162 return accept163 ? utils.parseAccept(accept)164 : [];165});166167/**168 * Return an array of Accepted languages169 * ordered from highest quality to lowest.170 *171 * Examples:172 *173 * Accept-Language: en;q=.5, en-us174 * ['en-us', 'en']175 *176 * @return {Array}177 * @api public178 */179180req.__defineGetter__('acceptedLanguages', function(){181 var accept = this.get('Accept-Language');182 return accept183 ? utils184 .parseQuality(accept)185 .map(function(obj){186 return obj.value;187 })188 : [];189});190191/**192 * Return an array of Accepted charsets193 * ordered from highest quality to lowest.194 *195 * Examples:196 *197 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8198 * ['unicode-1-1', 'iso-8859-5']199 *200 * @return {Array}201 * @api public202 */203204req.__defineGetter__('acceptedCharsets', function(){205 var accept = this.get('Accept-Charset');206 return accept207 ? utils208 .parseQuality(accept)209 .map(function(obj){210 return obj.value;211 })212 : [];213});214215/**216 * Return the value of param `name` when present or `defaultValue`.217 *218 * - Checks body params, ex: id=12, {"id":12}219 * - Checks route placeholders, ex: _/user/:id_220 * - Checks query string params, ex: ?id=12221 *222 * To utilize request bodies, `req.body`223 * should be an object. This can be done by using224 * the `connect.bodyParser()` middleware.225 *226 * @param {String} name227 * @param {Mixed} defaultValue228 * @return {String}229 * @api public230 */231232req.param = function(name, defaultValue){233 // req.body234 if (this.body && undefined !== this.body[name]) return this.body[name];235236 // route params237 if (this.params238 && this.params.hasOwnProperty(name)239 && undefined !== this.params[name]) {240 return this.params[name]; 241 }242243 // query-string244 if (undefined !== this.query[name]) return this.query[name]; 245246 return defaultValue;247};248249/**250 * Check if the incoming request contains the "Content-Type" 251 * header field, and it contains the give mime `type`.252 *253 * Examples:254 *255 * // With Content-Type: text/html; charset=utf-8256 * req.is('html');257 * req.is('text/html');258 * req.is('text/*');259 * // => true260 * 261 * // When Content-Type is application/json262 * req.is('json');263 * req.is('application/json');264 * req.is('application/*');265 * // => true266 * 267 * req.is('html');268 * // => false269 * 270 * Now within our route callbacks, we can use to to assert content types271 * such as "image/jpeg", "image/png", etc.272 * 273 * app.post('/image/upload', function(req, res, next){274 * if (req.is('image/*')) {275 * // do something276 * } else {277 * next();278 * }279 * });280 * 281 * @param {String} type282 * @return {Boolean}283 * @api public284 */285286req.is = function(type){287 var ct = this.get('Content-Type');288 if (!ct) return false;289 ct = ct.split(';')[0];290 if (!~type.indexOf('/')) type = mime.lookup(type);291 if (~type.indexOf('*')) {292 type = type.split('/');293 ct = ct.split('/');294 if ('*' == type[0] && type[1] == ct[1]) return true;295 if ('*' == type[1] && type[0] == ct[0]) return true;296 return false;297 }298 return !! ~ct.indexOf(type);299};300301/**302 * Return the protocol string "http" or "https"303 * when requested with TLS. When the "trust proxy" 304 * setting is enabled the "X-Forwarded-Proto" header305 * field will be trusted. If you're running behind306 * a reverse proxy that supplies https for you this307 * may be enabled.308 *309 * @return {String}310 * @api public311 */312313req.__defineGetter__('protocol', function(){314 var trustProxy = this.app.settings['trust proxy'];315 return this.connection.encrypted316 ? 'https'317 : trustProxy318 ? (this.get('X-Forwarded-Proto') || 'http')319 : 'http';320});321322/**323 * Short-hand for:324 *325 * req.protocol == 'https'326 *327 * @return {Boolean}328 * @api public329 */330331req.__defineGetter__('secure', function(){332 return 'https' == this.protocol;333});334335/**336 * When "trust proxy" is `true`, parse337 * the "X-Forwarded-For" ip address list.338 *339 * For example if the value were "client, proxy1, proxy2"340 * you would receive the array `["proxy2", "proxy1", "client"]`341 * where "proxy2" is the furthest down-stream.342 *343 * @return {Array}344 * @api public345 */346347req.__defineGetter__('ips', function(){348 var val = this.get('X-Forwarded-For');349 return val350 ? val.split(/ *, */).reverse()351 : [];352});353354/**355 * Return subdomains as an array.356 *357 * For example "tobi.ferrets.example.com"358 * would provide `["ferrets", "tobi"]`.359 *360 * @return {Array}361 * @api public362 */363364req.__defineGetter__('subdomains', function(){365 return this.get('Host')366 .split('.')367 .slice(0, -2)368 .reverse();369});370371/**372 * Short-hand for `url.parse(req.url).pathname`.373 *374 * @return {String}375 * @api public376 */377378req.__defineGetter__('path', function(){379 return parse(this.url).pathname;380});381382/**383 * Check if the request is fresh, aka384 * Last-Modified and/or the ETag385 * still match.386 *387 * @return {Boolean}388 * @api public389 */390391req.__defineGetter__('fresh', function(){392 return ! this.stale;393});394395/**396 * Check if the request is stale, aka397 * "Last-Modified" and / or the "ETag" for the398 * resource has changed.399 *400 * @return {Boolean}401 * @api public402 */403404req.__defineGetter__('stale', function(){405 return connect.utils.modified(this, this.res);406});407408/**409 * Check if the request was an _XMLHttpRequest_.410 *411 * @return {Boolean}412 * @api public413 */414415req.__defineGetter__('xhr', function(){416 var val = this.get('X-Requested-With') || '';417 return 'xmlhttprequest' == val.toLowerCase();418});