mirror of
https://github.com/zebrajr/express.git
synced 2026-01-15 12:15:27 +00:00
Added req.protocol()
This commit is contained in:
@@ -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
73
test/req.protocol.js
Normal 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();
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user