Skip to content

Commit

Permalink
Merge pull request #1761 from Leafly-com/fix/follow-redirect-cookies
Browse files Browse the repository at this point in the history
Fix incorrect response object being emitted on redirect
  • Loading branch information
titanism authored Jan 25, 2023
2 parents 4268ae4 + e2538f3 commit cd094f5
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/node/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
19 changes: 19 additions & 0 deletions test/node/redirects.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];

Expand Down
1 change: 1 addition & 0 deletions test/support/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
Expand Down

0 comments on commit cd094f5

Please sign in to comment.