nodejs / help

:sparkles: Need help with Node.js? File an Issue here. :rocket:
1.44k stars 276 forks source link

Fetch not working as expected for http status 407 #4344

Closed bdemann closed 4 months ago

bdemann commented 4 months ago

Details

If the server responds with a 407, fetch will fail in node with the following error.

Error: TypeError: fetch failed
    at node:internal/deps/undici/undici:12344:11
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async fetch407Endpoint (fourZeroSeven/fetch.js:22:22) {
  cause: Error
      at makeNetworkError (node:internal/deps/undici/undici:5585:35)
      at httpNetworkOrCacheFetch (node:internal/deps/undici/undici:10731:18)
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async httpFetch (node:internal/deps/undici/undici:10545:37)
      at async node:internal/deps/undici/undici:10342:20
      at async mainFetch (node:internal/deps/undici/undici:10332:20)
}

Sending the same request with cURL or fetch in Firefox results in the expected response with a 407 status I have more details and a simple reproduction of the error in this repo https://github.com/demergent-labs/fourZeroSeven

Node.js version

I have tried on the following node version: v18.18.0, v20.11.0 and v21.6.1

Example code

Here is the endpoint on the server

// Endpoint for 407 response
app.get('/407', (req, res) => {
  res.status(407).send('This is a 407 Proxy Authentication Required response.');
});

Here is the fetch request

async function fetch407Endpoint() {
  try {
    const response = await fetch('http://localhost:3000/407');
    if (response.status === 407) {
      const data = await response.text();
      console.log('407 endpoint response:', data);
    } else {
      console.log('407 endpoint didn\'t return with 407 status');
      console.error('Error:', response.status, response.statusText);
    }
  } catch (error) {
    console.log('407 endpoint failed');
    console.error('Error:', error);
  }
}

For more details see https://github.com/demergent-labs/fourZeroSeven

Operating system

Ubuntu 23.10

Scope

runtime

Module and version

fetch

VoltrexKeyva commented 4 months ago

The global fetch() API is provided by Undici, please open an issue there instead.

bdemann commented 4 months ago

Thank you for the direction, here is that issue https://github.com/nodejs/undici/issues/2896