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 0d59a66
Show file tree
Hide file tree
Showing 4 changed files with 22 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
10 changes: 9 additions & 1 deletion packages/node-fetch/src/Request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,15 @@ export class PonyfillRequest<TJSON = any> extends PonyfillBody<TJSON> implements
}
}

this._agent = requestInit?.agent;
if (requestInit?.agent != null) {
if (requestInit.agent === false) {
this._agent = false;
} else if (this.url.startsWith('http:/') && requestInit.agent instanceof HTTPAgent) {
this._agent = requestInit?.agent;
} else if (this.url.startsWith('https:/') && requestInit.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 0d59a66

Please sign in to comment.