From 5f5a5699b2d542321740b79374884e3b55fb0a6c Mon Sep 17 00:00:00 2001 From: Dom Harrington Date: Tue, 6 Dec 2016 17:21:48 -0800 Subject: [PATCH] Add support for reverse proxies by checking req.hostname or req.host. Fixes #20 This is so that the module works when express has `trust proxy` enabled and the `Host` header is expected to come from `X-Forwarded-Host` --- index.js | 4 +++- package.json | 1 + test/test.js | 41 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 8bd89bc..179eeb2 100644 --- a/index.js +++ b/index.js @@ -74,7 +74,9 @@ function vhost (hostname, handle) { */ function hostnameof (req) { - var host = req.headers.host + var host = req.hostname || // express v4 + req.host || // express v3 + req.headers.host // http if (!host) { return diff --git a/package.json b/package.json index eaf9ddc..24089f0 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "license": "MIT", "repository": "expressjs/vhost", "devDependencies": { + "connect": "^3.5.0", "eslint": "2.11.1", "eslint-config-standard": "5.3.1", "eslint-plugin-promise": "1.3.1", diff --git a/test/test.js b/test/test.js index d5f80b8..f284c1c 100644 --- a/test/test.js +++ b/test/test.js @@ -2,6 +2,7 @@ var assert = require('assert') var http = require('http') var request = require('supertest') +var connect = require('connect') var vhost = require('..') describe('vhost(hostname, server)', function () { @@ -22,6 +23,46 @@ describe('vhost(hostname, server)', function () { .expect(200, 'tobi', done) }) + it('should route by `req.hostname` (express v4)', function (done) { + var app = connect() + + app.use(function (req, res, next) { + req.hostname = 'anotherhost.com' + return next() + }) + + app.use(vhost('anotherhost.com', anotherhost)) + app.use(vhost('loki.com', loki)) + + function anotherhost (req, res) { res.end('anotherhost') } + function loki (req, res) { res.end('loki') } + + request(app) + .get('/') + .set('Host', 'tobi.com') + .expect(200, 'anotherhost', done) + }) + + it('should route by `req.host` (express v3)', function (done) { + var app = connect() + + app.use(function (req, res, next) { + req.host = 'anotherhost.com' + return next() + }) + + app.use(vhost('anotherhost.com', anotherhost)) + app.use(vhost('loki.com', loki)) + + function anotherhost (req, res) { res.end('anotherhost') } + function loki (req, res) { res.end('loki') } + + request(app) + .get('/') + .set('Host', 'tobi.com') + .expect(200, 'anotherhost', done) + }) + it('should ignore port in Host', function (done) { var app = createServer('tobi.com', function (req, res) { res.end('tobi')