Skip to content
Myr

request.js

This file

Path

lib/request.js

322 lines · 7.8 KiB · JavaScript

Last changed by

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

History of this file

Take it

The walk stopped after 200 commits: lines older than 1abb674 point at it.

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

lines 1–20why, 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')15 , mime = require('mime');1617/**18 * Default flash formatters.19 */20

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

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

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

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

Added `%d` flash formatterTj Holowaychukbefore adoptionc7c9606

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

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

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–95why, one step back
91 if (!regexp.exec(val)) return '';
92 return RegExp.$1 || RegExp.$2;93};9495/**

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

lines 96–135why, one step back
96 * Check if the _Accept_ header is present, and includes the given `type`.
97 *98 * When the _Accept_ header is not present `true` is returned. Otherwise99 * the given `type` is matched by an exact match, and then subtypes. You100 * may pass the subtype such as "html" which is then converted internally101 * to "text/html" using the mime lookup table.102 *103 * Examples:104 * 105 * // Accept: text/html106 * req.accepts('html');107 * // => true108 *109 * // Accept: text/*; application/json110 * req.accepts('html');111 * req.accepts('text/html');112 * req.accepts('text/plain');113 * req.accepts('application/json');114 * // => true115 *116 * req.accepts('image/png');117 * req.accepts('png');118 * // => false119 *120 * @param {String} type121 * @return {Boolean}122 * @api public123 */124125req.accepts = function(type){126 var accept = this.header('Accept');127128 // normalize extensions ".json" -> "json"129 if (type && '.' == type[0]) type = type.substr(1);130131 // when Accept does not exist, or is '*/*' return true 132 if (!accept || '*/*' == accept) {133 return true;134 } else if (type) {135 // allow "html" vs "text/html" etc

misc refactoringTj Holowaychukbefore adoption3dc53e1

line 136why, one step back
136 if (!~type.indexOf('/')) type = mime.lookup(type);

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

lines 137–142why, one step back
137
138 // check if we have a direct match139 if (~accept.indexOf(type)) return true;140141 // check if we have type/*142 type = type.split('/')[0] + '/*';

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

line 143why, one step back
143 return !! ~accept.indexOf(type);

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

lines 144–167why, one step back
144 } else {
145 return false;146 }147};148149/**150 * Return the value of param `name` when present or `defaultValue`.151 *152 * - Checks route placeholders, ex: _/user/:id_153 * - Checks query string params, ex: ?id=12154 * - Checks urlencoded body params, ex: id=12155 *156 * To utilize urlencoded request bodies, `req.body`157 * should be an object. This can be done by using158 * the `connect.bodyParser` middleware.159 *160 * @param {String} name161 * @param {Mixed} defaultValue162 * @return {String}163 * @api public164 */165166req.param = function(name, defaultValue){167 // route params like /user/:id

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

lines 168–170why, one step back
168 if (this.params
169 && this.params.hasOwnProperty(name)170 && undefined !== this.params[name]) {

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

lines 171–173why, one step back
171 return this.params[name];
172 }173 // query string params

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

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

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

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

refactored `req.param()`Tj Holowaychukbefore adoptiona4621a6

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

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

lines 179–208why, one step back
179 return defaultValue;
180};181182/**183 * Queue flash `msg` of the given `type`.184 *185 * Examples:186 *187 * req.flash('info', 'email sent');188 * req.flash('error', 'email delivery failed');189 * req.flash('info', 'email re-sent');190 * // => 2191 *192 * req.flash('info');193 * // => ['email sent', 'email re-sent']194 *195 * req.flash('info');196 * // => []197 *198 * req.flash();199 * // => { error: ['email delivery failed'], info: [] }200 *201 * Formatting:202 *203 * Flash notifications also support arbitrary formatting support.204 * For example you may pass variable arguments to `req.flash()`205 * and use the %s specifier to be replaced by the associated argument:206 *207 * req.flash('info', 'email has been sent to %s.', userName);208 *

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

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

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

line 212why, one step back
212 *

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

lines 213–218why, one step back
213 * app.formatters = {
214 * u: function(val){215 * return String(val).toUpperCase();216 * }217 * };218 *

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

lines 219–230why, one step back
219 * @param {String} type
220 * @param {String} msg221 * @return {Array|Object|Number}222 * @api public223 */224225req.flash = function(type, msg){226 if (this.session === undefined) throw Error('req.flash() requires sessions');227 var msgs = this.session.flash = this.session.flash || {};228 if (type && msg) {229 var i = 2230 , args = arguments

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

lines 231–232why, one step back
231 , formatters = this.app.formatters || {};
232 formatters.__proto__ = defaultFormatters;

Merge branch 'feature/router'Tj Holowaychukbefore adoption1d2dd2a

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

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

lines 234–304why, one step back
234 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){
235 var formatter = formatters[format];236 if (formatter) return formatter(args[i++]);237 });238 return (msgs[type] = msgs[type] || []).push(msg);239 } else if (type) {240 var arr = msgs[type];241 delete msgs[type];242 return arr || [];243 } else {244 this.session.flash = {};245 return msgs;246 }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 * // => true259 * 260 * // When Content-Type is application/json261 * req.is('json');262 * req.is('application/json');263 * // => true264 * 265 * req.is('html');266 * // => false267 * 268 * Ad-hoc callbacks can also be registered with Express, to perform269 * assertions again the request, for example if we need an expressive270 * way to check if our incoming request is an image, we can register "an image"271 * callback:272 * 273 * app.is('an image', function(req){274 * return 0 == req.headers['content-type'].indexOf('image');275 * });276 * 277 * Now within our route callbacks, we can use to to assert content types278 * such as "image/jpeg", "image/png", etc.279 * 280 * app.post('/image/upload', function(req, res, next){281 * if (req.is('an image')) {282 * // do something283 * } else {284 * next();285 * }286 * });287 * 288 * @param {String} type289 * @return {Boolean}290 * @api public291 */292293req.is = function(type){294 var fn = this.app.is(type);295 if (fn) return fn(this);296 var contentType = this.headers['content-type'];297 if (!contentType) return;298 if (!~type.indexOf('/')) type = mime.lookup(type);299 if (~type.indexOf('*')) {300 type = type.split('/')301 contentType = contentType.split('/');302 if ('*' == type[0] && type[1] == contentType[1]) return true;303 if ('*' == type[1] && type[0] == contentType[0]) return true;304 }

return bool from req.is()Tj Holowaychukbefore adoption6e633b3

line 305why, one step back
305 return !! ~contentType.indexOf(type);

temp fix for nodes res.removeHeader() after sent "bug"Tj Holowaychukbefore adoption1abb674

lines 306–322why, one step back
306};
307308// Callback for isXMLHttpRequest / xhr309310function isxhr() {311 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';312}313314/**315 * Check if the request was an _XMLHttpRequest_.316 *317 * @return {Boolean}318 * @api public319 */320321req.__defineGetter__('isXMLHttpRequest', isxhr);322req.__defineGetter__('xhr', isxhr);