request.js
This file
Path
lib/request.js
290 lines · 7.1 KiB · JavaScript
Last changed by
Renaming usage of old connect middlewareTj Holowaychukbefore adoption2a7a5ae
History of this fileTake it
moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 1–12why, one step back12/*!3 * Express - request4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var http = require('http')replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85
line 13why, one step back13 , req = http.IncomingMessage.prototypemoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
line 14why, one step back14 , utils = require('./utils')replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85
line 15why, one step back15 , mime = require('mime');moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 16–31why, one step back1617/**18 * Default flash formatters.19 *20 * @type Object21 */2223var flashFormatters = exports.flashFormatters = {24 s: function(val){25 return String(val);26 }27};2829/**30 * Return request header or optional default.31 *Added req.header() Referrer / Referer special-caseTj Holowaychukbefore adoptionb65b063
lines 32–35why, one step back32 * The `Referrer` header field is special-cased,33 * both `Referrer` and `Referer` will yield are34 * interchangeable.35 *moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 36–55why, one step back36 * Examples:37 *38 * req.header('Content-Type');39 * // => "text/plain"40 * 41 * req.header('content-type');42 * // => "text/plain"43 * 44 * req.header('Accept');45 * // => undefined46 * 47 * req.header('Accept', 'text/html');48 * // => "text/html"49 *50 * @param {String} name51 * @param {String} defaultValue52 * @return {String} 53 * @api public54 */55Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 56why, one step back56req.header = function(name, defaultValue){Added req.header() Referrer / Referer special-caseTj Holowaychukbefore adoptionb65b063
lines 57–59why, one step back57 switch (name = name.toLowerCase()) {58 case 'referer':59 case 'referrer':refactored res.redirect() with res.req.header() for referrerTj Holowaychukbefore adoption6993a27
lines 60–62why, one step back60 return this.headers.referrer61 || this.headers.referer62 || defaultValue;Added req.header() Referrer / Referer special-caseTj Holowaychukbefore adoptionb65b063
lines 63–65why, one step back63 default:64 return this.headers[name] || defaultValue;65 }moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 66–97why, one step back66};6768/**69 * Check if the _Accept_ header is present, and includes the given `type`.70 *71 * When the _Accept_ header is not present `true` is returned. Otherwise72 * the given `type` is matched by an exact match, and then subtypes. You73 * may pass the subtype such as "html" which is then converted internally74 * to "text/html" using the mime lookup table.75 *76 * Examples:77 * 78 * // Accept: text/html79 * req.accepts('html');80 * // => true81 *82 * // Accept: text/*; application/json83 * req.accepts('html');84 * req.accepts('text/html');85 * req.accepts('text/plain');86 * req.accepts('application/json');87 * // => true88 *89 * req.accepts('image/png');90 * req.accepts('png');91 * // => false92 *93 * @param {String} type94 * @return {Boolean}95 * @api public96 */97Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 98why, one step back98req.accepts = function(type){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 99–109why, one step back99 var accept = this.header('Accept');100101 // Normalize extensions ".json" -> "json"102 if (type && '.' == type[0]) type = type.substr(1);103104 // When Accept does not exist, or is '*/*' return true 105 if (!accept || '*/*' == accept) {106 return true;107 } else if (type) {108 // Allow "html" vs "text/html" etc109 if (type.indexOf('/') < 0) {replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85
line 110why, one step back110 type = mime.lookup(type);moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 111–132why, one step back111 }112113 // Check if we have a direct match114 if (~accept.indexOf(type)) return true;115116 // Check if we have type/*117 type = type.split('/')[0] + '/*';118 return accept.indexOf(type) >= 0;119 } else {120 return false;121 }122};123124/**125 * Return the value of param `name` when present or `defaultValue`.126 *127 * - Checks route placeholders, ex: _/user/:id_128 * - Checks query string params, ex: ?id=12129 * - Checks urlencoded body params, ex: id=12130 *131 * To utilize urlencoded request bodies, `req.body`132 * should be an object. This can be done by usingRenaming usage of old connect middlewareTj Holowaychukbefore adoption2a7a5ae
line 133why, one step back133 * the `connect.bodyParser` middleware.moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 134–140why, one step back134 *135 * @param {String} name136 * @param {Mixed} defaultValue137 * @return {String}138 * @api public139 */140Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 141why, one step back141req.param = function(name, defaultValue){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 142–149why, one step back142 // Route params like /user/:id143 if (this.params[name] !== undefined) {144 return this.params[name]; 145 }146 // Query string params147 if (this.query[name] !== undefined) {148 return this.query[name]; 149 }Renaming usage of old connect middlewareTj Holowaychukbefore adoption2a7a5ae
line 150why, one step back150 // Request body params via connect.bodyParsermoved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 151–191why, one step back151 if (this.body && this.body[name] !== undefined) {152 return this.body[name];153 }154 return defaultValue;155};156157/**158 * Queue flash `msg` of the given `type`.159 *160 * Examples:161 *162 * req.flash('info', 'email sent');163 * req.flash('error', 'email delivery failed');164 * req.flash('info', 'email re-sent');165 * // => 2166 *167 * req.flash('info');168 * // => ['email sent', 'email re-sent']169 *170 * req.flash('info');171 * // => []172 *173 * req.flash();174 * // => { error: ['email delivery failed'], info: [] }175 *176 * Formatting:177 *178 * Flash notifications also support arbitrary formatting support.179 * For example you may pass variable arguments to `req.flash()`180 * and use the %s specifier to be replaced by the associated argument:181 *182 * req.flash('info', 'email has been sent to %s.', userName);183 *184 * To add custom formatters use the `exports.flashFormatters` object.185 *186 * @param {String} type187 * @param {String} msg188 * @return {Array|Object|Number}189 * @api public190 */191Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 192why, one step back192req.flash = function(type, msg){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 193–258why, one step back193 var msgs = this.session.flash = this.session.flash || {};194 if (type && msg) {195 var i = 2196 , args = arguments197 , formatters = this.app.flashFormatters || {};198 formatters.__proto__ = flashFormatters;199 msg = utils.miniMarkdown(utils.htmlEscape(msg));200 msg = msg.replace(/%([a-zA-Z])/g, function(_, format){201 var formatter = formatters[format];202 if (formatter) return formatter(args[i++]);203 });204 return (msgs[type] = msgs[type] || []).push(msg);205 } else if (type) {206 var arr = msgs[type];207 delete msgs[type];208 return arr || [];209 } else {210 this.session.flash = {};211 return msgs;212 }213};214215/**216 * Check if the incoming request contains the "Content-Type" 217 * header field, and it contains the give mime `type`.218 *219 * Examples:220 *221 * // With Content-Type: text/html; charset=utf-8222 * req.is('html');223 * req.is('text/html');224 * // => true225 * 226 * // When Content-Type is application/json227 * req.is('json');228 * req.is('application/json');229 * // => true230 * 231 * req.is('html');232 * // => false233 * 234 * Ad-hoc callbacks can also be registered with Express, to perform235 * assertions again the request, for example if we need an expressive236 * way to check if our incoming request is an image, we can register "an image"237 * callback:238 * 239 * app.is('an image', function(req){240 * return 0 == req.headers['content-type'].indexOf('image');241 * });242 * 243 * Now within our route callbacks, we can use to to assert content types244 * such as "image/jpeg", "image/png", etc.245 * 246 * app.post('/image/upload', function(req, res, next){247 * if (req.is('an image')) {248 * // do something249 * } else {250 * next();251 * }252 * });253 * 254 * @param {String} type255 * @return {Boolean}256 * @api public257 */258Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
line 259why, one step back259req.is = function(type){moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 260–263why, one step back260 var fn = this.app.is(type);261 if (fn) return fn(this);262 var contentType = this.headers['content-type'];263 if (!contentType) return;replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85
line 264why, one step back264 if (!~type.indexOf('/')) type = mime.lookup(type);moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 265–288why, one step back265 // TODO: remove when connect no longer appends charset...266 if (~type.indexOf(';')) type = type.split(';')[0];267 if (~type.indexOf('*')) {268 type = type.split('/')269 contentType = contentType.split('/');270 if ('*' == type[0] && type[1] == contentType[1]) return true;271 if ('*' == type[1] && type[0] == contentType[0]) return true;272 }273 return ~contentType.indexOf(type);274};275276// Callback for isXMLHttpRequest / xhr277278function isxhr() {279 return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';280}281282/**283 * Check if the request was an _XMLHttpRequest_.284 *285 * @return {Boolean}286 * @api public287 */288Refactored req/res proto assignmentsTj Holowaychukbefore adoption99820e7
lines 289–290why, one step back289req.__defineGetter__('isXMLHttpRequest', isxhr);290req.__defineGetter__('xhr', isxhr);