request.js
This file
Path
lib/request.js
417 lines · 8.8 KiB · JavaScript
Last changed by
update headersTJ Holowaychukbefore adoptiona376980
History of this fileTake it
12/*!3 * Express - request4 * Copyright(c) 2010-2012 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 = connect.utils.parseUrl16 , 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` are interchangeable.31 *32 * Examples:33 *34 * req.get('Content-Type');35 * // => "text/plain"36 * 37 * req.get('content-type');38 * // => "text/plain"39 * 40 * req.get('Something');41 * // => undefined42 *43 * Aliased as `req.header()`.44 *45 * @param {String} name46 * @return {String} 47 * @api public48 */4950req.get = 51req.header = function(name){52 switch (name = name.toLowerCase()) {53 case 'referer':54 case 'referrer':55 return this.headers.referrer56 || this.headers.referer;57 default:58 return this.headers[name];59 }60};6162/**63 * Check if the given `type(s)` is acceptable, returning64 * the best match when true, otherwise `undefined`, in which65 * case you should respond with 406 "Not Acceptable".66 *67 * The `type` value may be a single mime type string68 * such as "application/json", the extension name69 * such as "json", a comma-delimted list such as "json, html, text/plain",70 * or an array `["json", "html", "text/plain"]`. When a list71 * or array is given the _best_ match, if any is returned.72 *73 * Examples:74 * 75 * // Accept: text/html76 * req.accepts('html');77 * // => "html"78 *79 * // Accept: text/*, application/json80 * req.accepts('html');81 * // => "html"82 * req.accepts('text/html');83 * // => "text/html"84 * req.accepts('json, text');85 * // => "json"86 * req.accepts('application/json');87 * // => "application/json"88 *89 * // Accept: text/*, application/json90 * req.accepts('image/png');91 * req.accepts('png');92 * // => undefined93 *94 * // Accept: text/*;q=.5, application/json95 * req.accepts(['html', 'json']);96 * req.accepts('html, json');97 * // => "json"98 *99 * @param {String|Array} type(s)100 * @return {String}101 * @api public102 */103104req.accepts = function(type){105 return utils.accepts(type, this.get('Accept'));106};107108/**109 * Check if the given `charset` is acceptable,110 * otherwise you should respond with 406 "Not Acceptable".111 *112 * @param {String} charset113 * @return {Boolean}114 * @api public115 */116117req.acceptsCharset = function(charset){118 var accepted = this.acceptedCharsets;119 return accepted.length120 ? ~accepted.indexOf(charset)121 : true;122};123124/**125 * Check if the given `lang` is acceptable,126 * otherwise you should respond with 406 "Not Acceptable".127 *128 * @param {String} lang129 * @return {Boolean}130 * @api public131 */132133req.acceptsLanguage = function(lang){134 var accepted = this.acceptedLanguages;135 return accepted.length136 ? ~accepted.indexOf(lang)137 : true;138};139140/**141 * Return an array of Accepted media types142 * ordered from highest quality to lowest.143 *144 * Examples:145 *146 * [ { value: 'application/json',147 * quality: 1,148 * type: 'application',149 * subtype: 'json' },150 * { value: 'text/html',151 * quality: 0.5,152 * type: 'text',153 * subtype: 'html' } ]154 *155 * @return {Array}156 * @api public157 */158159req.__defineGetter__('accepted', function(){160 var accept = this.get('Accept');161 return accept162 ? utils.parseAccept(accept)163 : [];164});165166/**167 * Return an array of Accepted languages168 * ordered from highest quality to lowest.169 *170 * Examples:171 *172 * Accept-Language: en;q=.5, en-us173 * ['en-us', 'en']174 *175 * @return {Array}176 * @api public177 */178179req.__defineGetter__('acceptedLanguages', function(){180 var accept = this.get('Accept-Language');181 return accept182 ? utils183 .parseQuality(accept)184 .map(function(obj){185 return obj.value;186 })187 : [];188});189190/**191 * Return an array of Accepted charsets192 * ordered from highest quality to lowest.193 *194 * Examples:195 *196 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8197 * ['unicode-1-1', 'iso-8859-5']198 *199 * @return {Array}200 * @api public201 */202203req.__defineGetter__('acceptedCharsets', function(){204 var accept = this.get('Accept-Charset');205 return accept206 ? utils207 .parseQuality(accept)208 .map(function(obj){209 return obj.value;210 })211 : [];212});213214/**215 * Return the value of param `name` when present or `defaultValue`.216 *217 * - Checks body params, ex: id=12, {"id":12}218 * - Checks route placeholders, ex: _/user/:id_219 * - Checks query string params, ex: ?id=12220 *221 * To utilize request bodies, `req.body`222 * should be an object. This can be done by using223 * the `connect.bodyParser()` middleware.224 *225 * @param {String} name226 * @param {Mixed} defaultValue227 * @return {String}228 * @api public229 */230231req.param = function(name, defaultValue){232 // req.body233 if (this.body && undefined !== this.body[name]) return this.body[name];234235 // route params236 if (this.params237 && this.params.hasOwnProperty(name)238 && undefined !== this.params[name]) {239 return this.params[name]; 240 }241242 // query-string243 if (undefined !== this.query[name]) return this.query[name]; 244245 return defaultValue;246};247248/**249 * Check if the incoming request contains the "Content-Type" 250 * header field, and it contains the give mime `type`.251 *252 * Examples:253 *254 * // With Content-Type: text/html; charset=utf-8255 * req.is('html');256 * req.is('text/html');257 * req.is('text/*');258 * // => true259 * 260 * // When Content-Type is application/json261 * req.is('json');262 * req.is('application/json');263 * req.is('application/*');264 * // => true265 * 266 * req.is('html');267 * // => false268 * 269 * Now within our route callbacks, we can use to to assert content types270 * such as "image/jpeg", "image/png" as shown here:271 * 272 * app.post('/image/upload', function(req, res, next){273 * if (req.is('image/*')) {274 * // do something275 * } else {276 * next();277 * }278 * });279 * 280 * @param {String} type281 * @return {Boolean}282 * @api public283 */284285req.is = function(type){286 var ct = this.get('Content-Type');287 if (!ct) return false;288 ct = ct.split(';')[0];289 if (!~type.indexOf('/')) type = mime.lookup(type);290 if (~type.indexOf('*')) {291 type = type.split('/');292 ct = ct.split('/');293 if ('*' == type[0] && type[1] == ct[1]) return true;294 if ('*' == type[1] && type[0] == ct[0]) return true;295 return false;296 }297 return !! ~ct.indexOf(type);298};299300/**301 * Return the protocol string "http" or "https"302 * when requested with TLS. When the "trust proxy" 303 * setting is enabled the "X-Forwarded-Proto" header304 * field will be trusted. If you're running behind305 * a reverse proxy that supplies https for you this306 * may be enabled.307 *308 * @return {String}309 * @api public310 */311312req.__defineGetter__('protocol', function(){313 var trustProxy = this.app.get('trust proxy');314 return this.connection.encrypted315 ? 'https'316 : trustProxy317 ? (this.get('X-Forwarded-Proto') || 'http')318 : 'http';319});320321/**322 * Short-hand for:323 *324 * req.protocol == 'https'325 *326 * @return {Boolean}327 * @api public328 */329330req.__defineGetter__('secure', function(){331 return 'https' == this.protocol;332});333334/**335 * When "trust proxy" is `true`, parse336 * the "X-Forwarded-For" ip address list.337 *338 * For example if the value were "client, proxy1, proxy2"339 * you would receive the array `["proxy2", "proxy1", "client"]`340 * where "proxy2" is the furthest down-stream.341 *342 * @return {Array}343 * @api public344 */345346req.__defineGetter__('ips', function(){347 var val = this.get('X-Forwarded-For');348 return val349 ? val.split(/ *, */).reverse()350 : [];351});352353/**354 * Return subdomains as an array.355 *356 * For example "tobi.ferrets.example.com"357 * would provide `["ferrets", "tobi"]`.358 *359 * @return {Array}360 * @api public361 */362363req.__defineGetter__('subdomains', function(){364 return this.get('Host')365 .split('.')366 .slice(0, -2)367 .reverse();368});369370/**371 * Short-hand for `url.parse(req.url).pathname`.372 *373 * @return {String}374 * @api public375 */376377req.__defineGetter__('path', function(){378 return parse(this).pathname;379});380381/**382 * Check if the request is fresh, aka383 * Last-Modified and/or the ETag384 * still match.385 *386 * @return {Boolean}387 * @api public388 */389390req.__defineGetter__('fresh', function(){391 return ! this.stale;392});393394/**395 * Check if the request is stale, aka396 * "Last-Modified" and / or the "ETag" for the397 * resource has changed.398 *399 * @return {Boolean}400 * @api public401 */402403req.__defineGetter__('stale', function(){404 return connect.utils.modified(this, this.res);405});406407/**408 * Check if the request was an _XMLHttpRequest_.409 *410 * @return {Boolean}411 * @api public412 */413414req.__defineGetter__('xhr', function(){415 var val = this.get('X-Requested-With') || '';416 return 'xmlhttprequest' == val.toLowerCase();417});