diff --git a/src/node/index.js b/src/node/index.js index ed1e46578..0bd89185d 100644 --- a/src/node/index.js +++ b/src/node/index.js @@ -551,12 +551,13 @@ Request.prototype._redirect = function (res) { _initHeaders(this); // redirect + this.res = res; this._endCalled = false; this.url = url; this.qs = {}; this._query.length = 0; this.set(headers); - this.emit('redirect', res); + this._emitRedirect(); this._redirectList.push(this.url); this.end(this._callback); return this; @@ -969,6 +970,18 @@ Request.prototype._emitResponse = function (body, files) { return response; }; +/** + * Emit `redirect` event, passing an instanceof `Response`. + * + * @api private + */ + +Request.prototype._emitRedirect = function () { + const response = new Response(this); + response.redirects = this._redirectList; + this.emit('redirect', response); +}; + Request.prototype.end = function (fn) { this.request(); debug('%s %s', this.method, this.url); diff --git a/test/node/redirects.js b/test/node/redirects.js index 7dff60fe8..b1d5d9260 100644 --- a/test/node/redirects.js +++ b/test/node/redirects.js @@ -71,6 +71,25 @@ describe('request', () => { }); }); + it('should overwrite previously set cookie during a redirect when agent is used', (done) => { + const agent = request.agent(); + agent.get(`${base}/set-cookie`).end((error) => { + assert.ifError(error); + agent + .get(`${base}/cookie-redirect`) + .redirects(1) + .end((error, res) => { + try { + assert.ifError(error); + assert(/replaced=yes/.test(res.text), 'replaced=yes'); + done(); + } catch (err) { + done(err); + } + }); + }); + }) + it('should follow Location', (done) => { const redirects = []; diff --git a/test/support/server.js b/test/support/server.js index 159da2753..a219c0d15 100644 --- a/test/support/server.js +++ b/test/support/server.js @@ -419,6 +419,7 @@ app.get('/cookie-redirect', (request, res) => { }); app.get('/set-cookie', (request, res) => { + res.cookie('replaced', 'no') res.cookie('persist', '123'); res.send('ok'); });