Skip to content

Commit 0d59a66

Browse files
committed
fix(node-fetch): redirects from http to https
1 parent dbf40c8 commit 0d59a66

File tree

4 files changed

+22
-2
lines changed

4 files changed

+22
-2
lines changed

.changeset/cyan-cougars-confess.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@whatwg-node/node-fetch': patch
3+
---
4+
5+
Fix redirects from http to https

packages/node-fetch/src/Request.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,15 @@ export class PonyfillRequest<TJSON = any> extends PonyfillBody<TJSON> implements
9797
}
9898
}
9999

100-
this._agent = requestInit?.agent;
100+
if (requestInit?.agent != null) {
101+
if (requestInit.agent === false) {
102+
this._agent = false;
103+
} else if (this.url.startsWith('http:/') && requestInit.agent instanceof HTTPAgent) {
104+
this._agent = requestInit?.agent;
105+
} else if (this.url.startsWith('https:/') && requestInit.agent instanceof HTTPSAgent) {
106+
this._agent = requestInit?.agent;
107+
}
108+
}
101109
}
102110

103111
headersSerializer?: HeadersSerializer;

packages/node-fetch/src/fetchCurl.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,8 @@ export function fetchCurl<TResponseJSON = any, TRequestJSON = any>(
138138
const ponyfillResponse = new PonyfillResponse(outputStream, {
139139
status,
140140
headers: headersInit,
141-
url: fetchRequest.url,
141+
url: curlHandle.getInfo(Curl.info.REDIRECT_URL)?.toString() || fetchRequest.url,
142+
redirected: Number(curlHandle.getInfo(Curl.info.REDIRECT_COUNT)) > 0,
142143
});
143144
resolve(ponyfillResponse);
144145
streamResolved = outputStream;

packages/node-fetch/tests/fetch.spec.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,12 @@ describe('Node Fetch Ponyfill', () => {
225225
const resJson = await response.json();
226226
expect(resJson.test).toBe('test');
227227
});
228+
it('handles redirect from http to https', async () => {
229+
const response = await fetchPonyfill('http://github.com');
230+
await response.text();
231+
expect(response.status).toBe(200);
232+
expect(response.url === 'https://github.com' || response.redirected).toBeTruthy();
233+
});
228234
},
229235
{ noNativeFetch: true },
230236
);

0 commit comments

Comments
 (0)