Skip to content

Commit

Permalink
fix(node-fetch): redirects from http to https
Browse files Browse the repository at this point in the history
  • Loading branch information
ardatan committed Jul 30, 2024
1 parent dbf40c8 commit 6c04b05
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/cyan-cougars-confess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@whatwg-node/node-fetch': patch
---

Fix redirects from http to https
11 changes: 10 additions & 1 deletion packages/node-fetch/src/Request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,16 @@ export class PonyfillRequest<TJSON = any> extends PonyfillBody<TJSON> implements
}
}

this._agent = requestInit?.agent;
if (requestInit?.agent != null) {
if (requestInit?.agent === false) {
this._agent = false;
}
if (this.url.startsWith('http:/') && this._agent instanceof HTTPAgent) {
this._agent = requestInit?.agent;
} else if (this.url.startsWith('https:/') && this._agent instanceof HTTPSAgent) {
this._agent = requestInit?.agent;
}
}
}

headersSerializer?: HeadersSerializer;
Expand Down
3 changes: 2 additions & 1 deletion packages/node-fetch/src/fetchCurl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@ export function fetchCurl<TResponseJSON = any, TRequestJSON = any>(
const ponyfillResponse = new PonyfillResponse(outputStream, {
status,
headers: headersInit,
url: fetchRequest.url,
url: curlHandle.getInfo(Curl.info.REDIRECT_URL)?.toString() || fetchRequest.url,
redirected: Number(curlHandle.getInfo(Curl.info.REDIRECT_COUNT)) > 0,
});
resolve(ponyfillResponse);
streamResolved = outputStream;
Expand Down
6 changes: 6 additions & 0 deletions packages/node-fetch/tests/fetch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,12 @@ describe('Node Fetch Ponyfill', () => {
const resJson = await response.json();
expect(resJson.test).toBe('test');
});
it('handles redirect from http to https', async () => {
const response = await fetchPonyfill('http://github.com');
await response.text();
expect(response.status).toBe(200);
expect(response.url === 'https://github.com' || response.redirected).toBeTruthy();
});
},
{ noNativeFetch: true },
);
Expand Down

0 comments on commit 6c04b05

Please sign in to comment.