Skip to content
Myr

request.js

This file

Path

lib/request.js

339 lines · 8.3 KiB · JavaScript

Last changed by

misc refactoringTj Holowaychukbefore adoption77d8823

History of this file

Take it

The walk stopped after 200 commits: lines older than 723774a point at it.

added quick start to guideTj Holowaychukbefore adoption723774a

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

added quick start to guideTj Holowaychukbefore adoption723774a

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.

added quick start to guideTj Holowaychukbefore adoption723774a

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 = {

misc refactoringTj Holowaychukbefore adoption77d8823

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 25–66why, one step back
25};
2627/**28 * Return request header or optional default.29 *30 * The `Referrer` header field is special-cased,31 * both `Referrer` and `Referer` will yield are32 * interchangeable.33 *34 * Examples:35 *36 * req.header('Content-Type');37 * // => "text/plain"38 * 39 * req.header('content-type');40 * // => "text/plain"41 * 42 * req.header('Accept');43 * // => undefined44 * 45 * req.header('Accept', 'text/html');46 * // => "text/html"47 *48 * @param {String} name49 * @param {String} defaultValue50 * @return {String} 51 * @api public52 */5354req.header = function(name, defaultValue){55 switch (name = name.toLowerCase()) {56 case 'referer':57 case 'referrer':58 return this.headers.referrer59 || this.headers.referer60 || defaultValue;61 default:62 return this.headers[name] || defaultValue;63 }64};6566/**

Merge branch 'param'Tj Holowaychukbefore adoption1820ea6

lines 67–70why, one step back
67 * Get `field`'s `param` value, defaulting to ''.
68 *69 * Examples:70 *

docs for req.get()Tj Holowaychukbefore adoption6bb100d

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

Merge branch 'param'Tj Holowaychukbefore adoption1820ea6

line 73why, one step back
73 *

examplesTj Holowaychukbefore adoption7eec21a

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

Merge branch 'param'Tj Holowaychukbefore adoption1820ea6

lines 77–85why, one step back
77 * @param {String} field
78 * @param {String} param79 * @return {String}80 * @api public81 */8283req.get = function(field, param){84 var val = this.header(field);85 if (!val) return '';

typoTj Holowaychukbefore adoptionf13ea34

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

Merge branch 'param'Tj Holowaychukbefore adoption1820ea6

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

Added shorthand for the parsed request's pathnameTj Holowaychukbefore adoptiond10b7b4

lines 90–100why, one step back
90
91/**92 * Short-hand for `require('url').parse(req.url).pathname`.93 *94 * @return {String}95 * @api public96 */9798req.__defineGetter__('path', function(){99 return parse(this.url).pathname;100});

Merge branch 'param'Tj Holowaychukbefore adoption1820ea6

lines 101–102why, one step back
101
102/**

added quick start to guideTj Holowaychukbefore adoption723774a

lines 103–132why, one step back
103 * Check if the _Accept_ header is present, and includes the given `type`.
104 *105 * When the _Accept_ header is not present `true` is returned. Otherwise106 * the given `type` is matched by an exact match, and then subtypes. You107 * may pass the subtype such as "html" which is then converted internally108 * to "text/html" using the mime lookup table.109 *110 * Examples:111 * 112 * // Accept: text/html113 * req.accepts('html');114 * // => true115 *116 * // Accept: text/*; application/json117 * req.accepts('html');118 * req.accepts('text/html');119 * req.accepts('text/plain');120 * req.accepts('application/json');121 * // => true122 *123 * req.accepts('image/png');124 * req.accepts('png');125 * // => false126 *127 * @param {String} type128 * @return {Boolean}129 * @api public130 */131132req.accepts = function(type){

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

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

added quick start to guideTj Holowaychukbefore adoption723774a

line 135why, one step back
135

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

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

added quick start to guideTj Holowaychukbefore adoption723774a

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

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

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

added quick start to guideTj Holowaychukbefore adoption723774a

line 141why, one step back
141

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

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

added quick start to guideTj Holowaychukbefore adoption723774a

line 144why, one step back
144

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

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

added quick start to guideTj Holowaychukbefore adoption723774a

line 147why, one step back
147

Refactored `req.accepts()`Tj Holowaychukbefore adoptionb1d4b71

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 151–171why, one step back
151};
152153/**154 * Return the value of param `name` when present or `defaultValue`.155 *156 * - Checks route placeholders, ex: _/user/:id_157 * - Checks query string params, ex: ?id=12158 * - Checks urlencoded body params, ex: id=12159 *160 * To utilize urlencoded request bodies, `req.body`161 * should be an object. This can be done by using162 * the `connect.bodyParser` middleware.163 *164 * @param {String} name165 * @param {Mixed} defaultValue166 * @return {String}167 * @api public168 */169170req.param = function(name, defaultValue){171 // route params like /user/:id

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

lines 172–174why, one step back
172 if (this.params
173 && this.params.hasOwnProperty(name)174 && undefined !== this.params[name]) {

added quick start to guideTj Holowaychukbefore adoption723774a

lines 175–177why, one step back
175 return this.params[name];
176 }177 // query string params

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

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

added quick start to guideTj Holowaychukbefore adoption723774a

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

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

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

added quick start to guideTj Holowaychukbefore adoption723774a

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

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

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 191–192why, one step back
191 * Examples:
192 *

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

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

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

lines 194–196why, one step back
194 * req.notify('info', 'email sent');
195 * req.notify('error', 'email delivery failed');196 * req.notify('info', 'email re-sent');

added quick start to guideTj Holowaychukbefore adoption723774a

lines 197–198why, one step back
197 * // => 2
198 *

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

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

added quick start to guideTj Holowaychukbefore adoption723774a

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

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 203–204why, one step back
203 * // => []
204 *

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 206–210why, one step back
206 * // => { error: ['email delivery failed'], info: [] }
207 *208 * Formatting:209 *210 * Flash notifications also support arbitrary formatting support.

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

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

added quick start to guideTj Holowaychukbefore adoption723774a

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

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

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

added quick start to guideTj Holowaychukbefore adoption723774a

line 215why, one step back
215 *

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

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

added quick start to guideTj Holowaychukbefore adoption723774a

line 219why, one step back
219 *

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

lines 220–225why, one step back
220 * app.formatters = {
221 * u: function(val){222 * return String(val).toUpperCase();223 * }224 * };225 *

added quick start to guideTj Holowaychukbefore adoption723774a

lines 226–231why, one step back
226 * @param {String} type
227 * @param {String} msg228 * @return {Array|Object|Number}229 * @api public230 */231

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

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

Removed `req.flash()` referencesTj Holowaychukbefore adoption3ab3702

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

refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6

line 236why, one step back
236

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

lines 237–252why, one step back
237 switch (arguments.length) {
238 // flush all messages239 case 0:240 sess.notifications = {};241 return msgs242 // flush messages for a specific type243 case 1:244 var arr = msgs[type];245 delete msgs[type];246 return arr || [];247 // set notification message248 default:249 var i = 2250 , args = arguments251 , formatters = this.app.formatters || {};252 formatters.__proto__ = defaultFormatters;

Fixed `req.notify()`, only escape argsTj Holowaychukbefore adoptionedb1dc0

line 253why, one step back
253 msg = utils.miniMarkdown(msg);

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

lines 254–255why, one step back
254 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){
255 var formatter = formatters[format];

Fixed `req.notify()`, only escape argsTj Holowaychukbefore adoptionedb1dc0

line 256why, one step back
256 if (formatter) return formatter(utils.escape(args[i++]));

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

lines 257–258why, one step back
257 });
258 return (msgs[type] = msgs[type] || []).push(msg);

refactored `req.flash()`Tj Holowaychukbefore adoption5982fa6

line 259why, one step back
259 }

added quick start to guideTj Holowaychukbefore adoption723774a

lines 260–288why, one step back
260};
261262/**263 * Check if the incoming request contains the "Content-Type" 264 * header field, and it contains the give mime `type`.265 *266 * Examples:267 *268 * // With Content-Type: text/html; charset=utf-8269 * req.is('html');270 * req.is('text/html');271 * // => true272 * 273 * // When Content-Type is application/json274 * req.is('json');275 * req.is('application/json');276 * // => true277 * 278 * req.is('html');279 * // => false280 * 281 * Ad-hoc callbacks can also be registered with Express, to perform282 * assertions again the request, for example if we need an expressive283 * way to check if our incoming request is an image, we can register "an image"284 * callback:285 * 286 * app.is('an image', function(req){287 * return 0 == req.headers['content-type'].indexOf('image');288 * });

another `req.is()` exampleTj Holowaychukbefore adoption4b8e08d

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 294–316why, one step back
294 * Now within our route callbacks, we can use to to assert content types
295 * such as "image/jpeg", "image/png", etc.296 * 297 * app.post('/image/upload', function(req, res, next){298 * if (req.is('an image')) {299 * // do something300 * } else {301 * next();302 * }303 * });304 * 305 * @param {String} type306 * @return {Boolean}307 * @api public308 */309310req.is = function(type){311 var fn = this.app.is(type);312 if (fn) return fn(this);313 var contentType = this.headers['content-type'];314 if (!contentType) return;315 if (!~type.indexOf('/')) type = mime.lookup(type);316 if (~type.indexOf('*')) {

semiTj Holowaychukbefore adoption82c78ec

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

added quick start to guideTj Holowaychukbefore adoption723774a

lines 318–339why, one step back
318 contentType = contentType.split('/');
319 if ('*' == type[0] && type[1] == contentType[1]) return true;320 if ('*' == type[1] && type[0] == contentType[0]) return true;321 }322 return !! ~contentType.indexOf(type);323};324325// Callback for isXMLHttpRequest / xhr326327function isxhr() {328 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';329}330331/**332 * Check if the request was an _XMLHttpRequest_.333 *334 * @return {Boolean}335 * @api public336 */337338req.__defineGetter__('isXMLHttpRequest', isxhr);339req.__defineGetter__('xhr', isxhr);