From de056d2c904ae19f3bc3ac2b3015f88f06915bab Mon Sep 17 00:00:00 2001 From: Stefan Lau Date: Tue, 25 Sep 2018 13:29:04 +0200 Subject: [PATCH] Set host header instead of host in url Setting the host in the url might result in the request going to a completely different server (wherever the hostname resolves to), not necessarily the server under test. --- lib/agent.js | 3 +++ lib/test.js | 8 ++++---- test/supertest.js | 5 +++-- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/lib/agent.js b/lib/agent.js index 54ce47f1..ed016171 100644 --- a/lib/agent.js +++ b/lib/agent.js @@ -53,6 +53,9 @@ methods.forEach(function(method) { req.ca(this._ca); req.cert(this._cert); req.key(this._key); + if (this._host) { + req.set('host', this._host); + } req.on('response', this._saveCookies.bind(this)); req.on('redirect', this._saveCookies.bind(this)); diff --git a/lib/test.js b/lib/test.js index 6ad9c890..d804ea5d 100644 --- a/lib/test.js +++ b/lib/test.js @@ -25,7 +25,7 @@ module.exports = Test; * @api public */ -function Test(app, method, path, host) { +function Test(app, method, path) { Request.call(this, method.toUpperCase(), path); this.redirects(0); this.buffer(); @@ -33,7 +33,7 @@ function Test(app, method, path, host) { this._asserts = []; this.url = typeof app === 'string' ? app + path - : this.serverAddress(app, path, host); + : this.serverAddress(app, path); } /** @@ -51,7 +51,7 @@ Object.setPrototypeOf(Test.prototype, Request.prototype); * @api private */ -Test.prototype.serverAddress = function(app, path, host) { +Test.prototype.serverAddress = function(app, path) { var addr = app.address(); var port; var protocol; @@ -59,7 +59,7 @@ Test.prototype.serverAddress = function(app, path, host) { if (!addr) this._server = app.listen(0); port = app.address().port; protocol = app instanceof https.Server ? 'https' : 'http'; - return protocol + '://' + (host || '127.0.0.1') + ':' + port + path; + return protocol + '://127.0.0.1:' + port + path; }; /** diff --git a/test/supertest.js b/test/supertest.js index af708780..9b70ab5a 100644 --- a/test/supertest.js +++ b/test/supertest.js @@ -866,14 +866,15 @@ describe('agent.host(host)', function () { const agent = request.agent(app); app.get('/', function (req, res) { - res.send(); + res.send({ hostname: req.hostname }); }); agent .host('something.test') .get('/') .end(function (err, res) { - err.hostname.should.equal('something.test'); + if (err) return done(err); + res.body.hostname.should.equal('something.test'); done(); }); });