Skip to content

Commit e2538f3

Browse files
committedJan 24, 2023
fix(redirects): emit correct response in redirect event
1 parent bc627ea commit e2538f3

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed
 

‎src/node/index.js

+14-1
Original file line numberDiff line numberDiff line change
@@ -551,12 +551,13 @@ Request.prototype._redirect = function (res) {
551551
_initHeaders(this);
552552

553553
// redirect
554+
this.res = res;
554555
this._endCalled = false;
555556
this.url = url;
556557
this.qs = {};
557558
this._query.length = 0;
558559
this.set(headers);
559-
this.emit('redirect', res);
560+
this._emitRedirect();
560561
this._redirectList.push(this.url);
561562
this.end(this._callback);
562563
return this;
@@ -969,6 +970,18 @@ Request.prototype._emitResponse = function (body, files) {
969970
return response;
970971
};
971972

973+
/**
974+
* Emit `redirect` event, passing an instanceof `Response`.
975+
*
976+
* @api private
977+
*/
978+
979+
Request.prototype._emitRedirect = function () {
980+
const response = new Response(this);
981+
response.redirects = this._redirectList;
982+
this.emit('redirect', response);
983+
};
984+
972985
Request.prototype.end = function (fn) {
973986
this.request();
974987
debug('%s %s', this.method, this.url);

‎test/node/redirects.js

+19
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,25 @@ describe('request', () => {
7171
});
7272
});
7373

74+
it('should overwrite previously set cookie during a redirect when agent is used', (done) => {
75+
const agent = request.agent();
76+
agent.get(`${base}/set-cookie`).end((error) => {
77+
assert.ifError(error);
78+
agent
79+
.get(`${base}/cookie-redirect`)
80+
.redirects(1)
81+
.end((error, res) => {
82+
try {
83+
assert.ifError(error);
84+
assert(/replaced=yes/.test(res.text), 'replaced=yes');
85+
done();
86+
} catch (err) {
87+
done(err);
88+
}
89+
});
90+
});
91+
})
92+
7493
it('should follow Location', (done) => {
7594
const redirects = [];
7695

‎test/support/server.js

+1
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,7 @@ app.get('/cookie-redirect', (request, res) => {
419419
});
420420

421421
app.get('/set-cookie', (request, res) => {
422+
res.cookie('replaced', 'no')
422423
res.cookie('persist', '123');
423424
res.send('ok');
424425
});

0 commit comments

Comments
 (0)
Please sign in to comment.