Skip to content

Commit

Permalink
Added req.get(field, param)
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed Jun 21, 2011
1 parent 943e9b3 commit 4d96479
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/request.js
Expand Up @@ -65,6 +65,28 @@ req.header = function(name, defaultValue){
}
};

/**
* Get `field`'s `param` value, defaulting to ''.
*
* Examples:
*
* req.get('content-disposition', 'filename');
* // => "something.png"
*
* @param {String} field
* @param {String} param
* @return {String}
* @api public
*/

req.get = function(field, param){
var val = this.header(field);
if (!val) return '';
var regexp = new RegExp(key + ' *= *(?:"([^"]+)"|([^;]+))', 'i');
if (!regexp.exec(val)) return '';
return RegExp.$1 || RegExp.$2;
};

/**
* Check if the _Accept_ header is present, and includes the given `type`.
*
Expand Down
31 changes: 31 additions & 0 deletions test/request.test.js
Expand Up @@ -303,5 +303,36 @@ module.exports = {
assert.response(app,
{ url: '/incorrect', headers: { Referer: 'expressjs.com' }},
{ body: 'expressjs.com' });
},

'test #get(field, param)': function(){
var app = express.createServer();

app.get('/', function(req, res, next){
req.get('content-disposition', 'filename')
.should.equal('foo bar.jpg');

req.get('Content-Disposition', 'filename')
.should.equal('foo bar.jpg');

req.get('x-content-foo', 'foo').should.equal('bar');
req.get('x-content-foo', 'bar').should.equal('foo bar baz');
req.get('x-content-foo', 'woot').should.equal('tobi loki jane');
req.get('cache-control', 'max-age').should.equal('500');

req.get('foo').should.equal('');
req.get('foo', 'bar').should.equal('');
res.end();
});

var fields = {
'Content-Disposition': 'attachment; filename="foo bar.jpg"'
, 'X-Content-Foo': 'foo=bar; bar=foo bar baz; woot=tobi loki jane;'
, 'Cache-Control': 'max-age = 500'
};

assert.response(app,
{ url: '/', headers: fields },
{ body: '' });
}
};

0 comments on commit 4d96479

Please sign in to comment.