Skip to content
Myr

request.js

This file

Path

lib/request.js

343 lines · 8.4 KiB · JavaScript

Last changed by

Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4

History of this file

Take it

The walk stopped after 200 commits: lines older than 85df59a point at it.

comma firstTj Holowaychukbefore adoption85df59a

lines 1–14why, one step back
1
2/*!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 , req = http.IncomingMessage.prototype14 , utils = require('./utils')

Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4

line 15why, one step back
15 , parse = require('url').parse

comma firstTj Holowaychukbefore adoption85df59a

lines 16–18why, one step back
16 , mime = require('mime');
1718/**

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

line 19why, one step back
19 * Default notification formatters.

comma firstTj Holowaychukbefore adoption85df59a

lines 20–21why, one step back
20 */
21

Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe

line 22why, one step back
22var defaultFormatters = exports.formatters = {

comma firstTj Holowaychukbefore adoption85df59a

lines 23–24why, one step back
23 s: function(val){
24 return String(val);

Added `%d` flash formatterTj Holowaychukbefore adoptionc7c9606

lines 25–27why, one step back
25 },
26 d: function(val){27 return val | 0;

comma firstTj Holowaychukbefore adoption85df59a

lines 28–70why, one step back
28 }
29};3031/**32 * Return request header or optional default.33 *34 * The `Referrer` header field is special-cased,35 * both `Referrer` and `Referer` will yield are36 * interchangeable.37 *38 * Examples:39 *40 * req.header('Content-Type');41 * // => "text/plain"42 * 43 * req.header('content-type');44 * // => "text/plain"45 * 46 * req.header('Accept');47 * // => undefined48 * 49 * req.header('Accept', 'text/html');50 * // => "text/html"51 *52 * @param {String} name53 * @param {String} defaultValue54 * @return {String} 55 * @api public56 */5758req.header = function(name, defaultValue){59 switch (name = name.toLowerCase()) {60 case 'referer':61 case 'referrer':62 return this.headers.referrer63 || this.headers.referer64 || defaultValue;65 default:66 return this.headers[name] || defaultValue;67 }68};6970/**

Merge branch 'param'Tj Holowaychukbefore adoption1820ea6

lines 71–74why, one step back
71 * Get `field`'s `param` value, defaulting to ''.
72 *73 * Examples:74 *

docs for req.get()Tj Holowaychukbefore adoption6bb100d

lines 75–76why, one step back
75 * req.get('content-disposition', 'filename');
76 * // => "something.png"

Merge branch 'param'Tj Holowaychukbefore adoption1820ea6

line 77why, one step back
77 *

examplesTj Holowaychukbefore adoption7eec21a

lines 78–80why, one step back
78 * req.get('content-disposition', 'rawr');
79 * // => ""80 *

Merge branch 'param'Tj Holowaychukbefore adoption1820ea6

lines 81–89why, one step back
81 * @param {String} field
82 * @param {String} param83 * @return {String}84 * @api public85 */8687req.get = function(field, param){88 var val = this.header(field);89 if (!val) return '';

typoTj Holowaychukbefore adoptionf13ea34

line 90why, one step back
90 var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');

Merge branch 'param'Tj Holowaychukbefore adoption1820ea6

lines 91–93why, one step back
91 if (!regexp.exec(val)) return '';
92 return RegExp.$1 || RegExp.$2;93};

Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4

lines 94–104why, one step back
94
95/**96 * Short-hand for `require('url').parse(req.url).pathname`.97 *98 * @return {String}99 * @api public100 */101102req.__defineGetter__('path', function(){103 return parse(this.url).pathname;104});

Merge branch 'param'Tj Holowaychukbefore adoption1820ea6

lines 105–106why, one step back
105
106/**

comma firstTj Holowaychukbefore adoption85df59a

lines 107–136why, one step back
107 * Check if the _Accept_ header is present, and includes the given `type`.
108 *109 * When the _Accept_ header is not present `true` is returned. Otherwise110 * the given `type` is matched by an exact match, and then subtypes. You111 * may pass the subtype such as "html" which is then converted internally112 * to "text/html" using the mime lookup table.113 *114 * Examples:115 * 116 * // Accept: text/html117 * req.accepts('html');118 * // => true119 *120 * // Accept: text/*; application/json121 * req.accepts('html');122 * req.accepts('text/html');123 * req.accepts('text/plain');124 * req.accepts('application/json');125 * // => true126 *127 * req.accepts('image/png');128 * req.accepts('png');129 * // => false130 *131 * @param {String} type132 * @return {Boolean}133 * @api public134 */135136req.accepts = function(type){

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 137–138why, one step back
137 var accept = this.header('Accept')
138 , type = String(type);

comma firstTj Holowaychukbefore adoption85df59a

line 139why, one step back
139

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 140–142why, one step back
140 // when not present or "*/*" accept anything
141 if (!accept || '*/*' == accept) return true;142

comma firstTj Holowaychukbefore adoption85df59a

line 143why, one step back
143 // normalize extensions ".json" -> "json"

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

line 144why, one step back
144 if ('.' == type[0]) type = type.substr(1);

comma firstTj Holowaychukbefore adoption85df59a

line 145why, one step back
145

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 146–147why, one step back
146 // allow "html" vs "text/html" etc
147 if (!~type.indexOf('/')) type = mime.lookup(type);

comma firstTj Holowaychukbefore adoption85df59a

line 148why, one step back
148

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 149–150why, one step back
149 // check if we have a direct match
150 if (~accept.indexOf(type)) return true;

comma firstTj Holowaychukbefore adoption85df59a

line 151why, one step back
151

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

lines 152–154why, one step back
152 // check if we have type/*
153 type = type.split('/')[0] + '/*';154 return !! ~accept.indexOf(type);

comma firstTj Holowaychukbefore adoption85df59a

lines 155–175why, one step back
155};
156157/**158 * Return the value of param `name` when present or `defaultValue`.159 *160 * - Checks route placeholders, ex: _/user/:id_161 * - Checks query string params, ex: ?id=12162 * - Checks urlencoded body params, ex: id=12163 *164 * To utilize urlencoded request bodies, `req.body`165 * should be an object. This can be done by using166 * the `connect.bodyParser` middleware.167 *168 * @param {String} name169 * @param {Mixed} defaultValue170 * @return {String}171 * @api public172 */173174req.param = function(name, defaultValue){175 // route params like /user/:id

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

lines 176–178why, one step back
176 if (this.params
177 && this.params.hasOwnProperty(name)178 && undefined !== this.params[name]) {

comma firstTj Holowaychukbefore adoption85df59a

lines 179–181why, one step back
179 return this.params[name];
180 }181 // query string params

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

lines 182–183why, one step back
182 if (undefined !== this.query[name]) return this.query[name];
183

comma firstTj Holowaychukbefore adoption85df59a

line 184why, one step back
184 // request body params via connect.bodyParser

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

lines 185–186why, one step back
185 if (this.body && undefined !== this.body[name]) return this.body[name];
186

comma firstTj Holowaychukbefore adoption85df59a

lines 187–192why, one step back
187 return defaultValue;
188};189190/**191 * Queue flash `msg` of the given `type`.192 *

Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30

lines 193–194why, one step back
193 * This method is aliased as `req.notify()`.
194 *

comma firstTj Holowaychukbefore adoption85df59a

lines 195–196why, one step back
195 * Examples:
196 *

Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30

line 197why, one step back
197 * req.notify('info', 'email sent');

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

lines 198–200why, one step back
198 * req.notify('info', 'email sent');
199 * req.notify('error', 'email delivery failed');200 * req.notify('info', 'email re-sent');

comma firstTj Holowaychukbefore adoption85df59a

lines 201–202why, one step back
201 * // => 2
202 *

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

line 203why, one step back
203 * req.notify('info');

comma firstTj Holowaychukbefore adoption85df59a

lines 204–205why, one step back
204 * // => ['email sent', 'email re-sent']
205 *

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

line 206why, one step back
206 * req.notify('info');

comma firstTj Holowaychukbefore adoption85df59a

lines 207–208why, one step back
207 * // => []
208 *

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

line 209why, one step back
209 * req.notify();

comma firstTj Holowaychukbefore adoption85df59a

lines 210–214why, one step back
210 * // => { error: ['email delivery failed'], info: [] }
211 *212 * Formatting:213 *214 * Flash notifications also support arbitrary formatting support.

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

line 215why, one step back
215 * For example you may pass variable arguments to `req.notify()`

comma firstTj Holowaychukbefore adoption85df59a

lines 216–217why, one step back
216 * and use the %s specifier to be replaced by the associated argument:
217 *

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

line 218why, one step back
218 * req.notify('info', 'email has been sent to %s.', userName);

comma firstTj Holowaychukbefore adoption85df59a

line 219why, one step back
219 *

Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe

lines 220–222why, one step back
220 * You may add addition formatters by defining `app.formatters`,
221 * for example in the following snippet we define `%u` to uppercase222 * a string:

comma firstTj Holowaychukbefore adoption85df59a

line 223why, one step back
223 *

Renamed `app.flashFormatters` to `app.formatters`Tj Holowaychukbefore adoption96b72fe

lines 224–229why, one step back
224 * app.formatters = {
225 * u: function(val){226 * return String(val).toUpperCase();227 * }228 * };229 *

comma firstTj Holowaychukbefore adoption85df59a

lines 230–235why, one step back
230 * @param {String} type
231 * @param {String} msg232 * @return {Array|Object|Number}233 * @api public234 */235

Added `req.notify()` alias of `req.flash()`Tj Holowaychukbefore adoption9413d30

line 236why, one step back
236req.notify = function(type, msg){

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

lines 237–239why, one step back
237 var sess = this.session;
238 if (null == sess) throw Error('req.notify() requires sessions');239 var msgs = sess.notifications = sess.notifications || {};

refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6

line 240why, one step back
240

make `req.notify()` arity basedTj Holowaychukbefore adoptionfd5d107

lines 241–262why, one step back
241 switch (arguments.length) {
242 // flush all messages243 case 0:244 sess.notifications = {};245 return msgs246 // flush messages for a specific type247 case 1:248 var arr = msgs[type];249 delete msgs[type];250 return arr || [];251 // set notification message252 default:253 var i = 2254 , args = arguments255 , formatters = this.app.formatters || {};256 formatters.__proto__ = defaultFormatters;257 msg = utils.miniMarkdown(utils.escape(msg));258 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){259 var formatter = formatters[format];260 if (formatter) return formatter(args[i++]);261 });262 return (msgs[type] = msgs[type] || []).push(msg);

refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6

line 263why, one step back
263 }

comma firstTj Holowaychukbefore adoption85df59a

lines 264–292why, one step back
264};
265266/**267 * Check if the incoming request contains the "Content-Type" 268 * header field, and it contains the give mime `type`.269 *270 * Examples:271 *272 * // With Content-Type: text/html; charset=utf-8273 * req.is('html');274 * req.is('text/html');275 * // => true276 * 277 * // When Content-Type is application/json278 * req.is('json');279 * req.is('application/json');280 * // => true281 * 282 * req.is('html');283 * // => false284 * 285 * Ad-hoc callbacks can also be registered with Express, to perform286 * assertions again the request, for example if we need an expressive287 * way to check if our incoming request is an image, we can register "an image"288 * callback:289 * 290 * app.is('an image', function(req){291 * return 0 == req.headers['content-type'].indexOf('image');292 * });

another `req.is()` exampleTj Holowaychukbefore adoption4b8e08d

lines 293–297why, one step back
293 *
294 * app.is('an attachment', function(req){295 * return 0 == req.headers['content-disposition'].indexOf('attachment');296 * });297 *

comma firstTj Holowaychukbefore adoption85df59a

lines 298–320why, one step back
298 * Now within our route callbacks, we can use to to assert content types
299 * such as "image/jpeg", "image/png", etc.300 * 301 * app.post('/image/upload', function(req, res, next){302 * if (req.is('an image')) {303 * // do something304 * } else {305 * next();306 * }307 * });308 * 309 * @param {String} type310 * @return {Boolean}311 * @api public312 */313314req.is = function(type){315 var fn = this.app.is(type);316 if (fn) return fn(this);317 var contentType = this.headers['content-type'];318 if (!contentType) return;319 if (!~type.indexOf('/')) type = mime.lookup(type);320 if (~type.indexOf('*')) {

semiTj Holowaychukbefore adoption82c78ec

line 321why, one step back
321 type = type.split('/');

comma firstTj Holowaychukbefore adoption85df59a

lines 322–343why, one step back
322 contentType = contentType.split('/');
323 if ('*' == type[0] && type[1] == contentType[1]) return true;324 if ('*' == type[1] && type[0] == contentType[0]) return true;325 }326 return !! ~contentType.indexOf(type);327};328329// Callback for isXMLHttpRequest / xhr330331function isxhr() {332 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';333}334335/**336 * Check if the request was an _XMLHttpRequest_.337 *338 * @return {Boolean}339 * @api public340 */341342req.__defineGetter__('isXMLHttpRequest', isxhr);343req.__defineGetter__('xhr', isxhr);