diff --git a/.changeset/cyan-cougars-confess.md b/.changeset/cyan-cougars-confess.md new file mode 100644 index 00000000000..184a726efd7 --- /dev/null +++ b/.changeset/cyan-cougars-confess.md @@ -0,0 +1,5 @@ +--- +'@whatwg-node/node-fetch': patch +--- + +Fix redirects from http to https diff --git a/packages/node-fetch/src/Request.ts b/packages/node-fetch/src/Request.ts index 96e6ef8f55e..7c42db3aa12 100644 --- a/packages/node-fetch/src/Request.ts +++ b/packages/node-fetch/src/Request.ts @@ -97,7 +97,16 @@ export class PonyfillRequest extends PonyfillBody 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; diff --git a/packages/node-fetch/src/fetchCurl.ts b/packages/node-fetch/src/fetchCurl.ts index df67be2795c..14eedefcdbd 100644 --- a/packages/node-fetch/src/fetchCurl.ts +++ b/packages/node-fetch/src/fetchCurl.ts @@ -138,7 +138,8 @@ export function fetchCurl( 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; diff --git a/packages/node-fetch/tests/fetch.spec.ts b/packages/node-fetch/tests/fetch.spec.ts index 4a69f5c47f8..f41d5fdb8a5 100644 --- a/packages/node-fetch/tests/fetch.spec.ts +++ b/packages/node-fetch/tests/fetch.spec.ts @@ -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 }, );