Added req.protocol()

This commit is contained in:
TJ Holowaychuk
2012-02-07 04:39:10 -08:00
parent ff92afa557
commit 2ba343d2b5
2 changed files with 91 additions and 0 deletions

View File

@@ -310,6 +310,24 @@ req.is = function(type){
return !! ~ct.indexOf(type);
};
/**
* Return the protocol string "http" or "https",
* while optionally trusting X-Forwarded-Proto
* when running behind a reverse proxy.
*
* @param {Boolean} trustProxy
* @return {String}
* @api public
*/
req.protocol = function(trustProxy){
return this.secure
? 'https'
: trustProxy
? (this.header('X-Forwarded-Proto') || 'http')
: 'http';
};
/**
* Short-hand for `req.connection.encrypted`.
*

73
test/req.protocol.js Normal file
View File

@@ -0,0 +1,73 @@
var express = require('../')
, request = require('./support/http');
describe('req', function(){
describe('.protocol(trustProxy)', function(){
it('should return the protocol string', function(done){
var app = express();
app.use(function(req, res){
res.end(req.protocol());
});
request(app)
.get('/')
.end(function(res){
res.body.should.equal('http');
done();
})
})
describe('when trustProxy is true', function(){
it('should respect X-Forwarded-Proto', function(done){
var app = express();
app.use(function(req, res){
res.end(req.protocol(true));
});
request(app)
.get('/')
.set('X-Forwarded-Proto', 'https')
.end(function(res){
res.body.should.equal('https');
done();
})
})
it('should default to http', function(done){
var app = express();
app.use(function(req, res){
res.end(req.protocol(true));
});
request(app)
.get('/')
.end(function(res){
res.body.should.equal('http');
done();
})
})
})
describe('when trustProxy is false', function(){
it('should ignore X-Forwarded-Proto', function(done){
var app = express();
app.use(function(req, res){
res.end(req.protocol());
});
request(app)
.get('/')
.set('X-Forwarded-Proto', 'https')
.end(function(res){
res.body.should.equal('http');
done();
})
})
})
})
})