bun icon indicating copy to clipboard operation
bun copied to clipboard

ConnectionRefused when `fetch()` is localhost

Open Electroid opened this issue 3 years ago • 42 comments
trafficstars

What version of Bun is running?

0.2.2

What platform is your computer?

Darwin 21.5.0 Darwin Kernel Version 21.5.0: Tue Apr 26 20:57:23 PDT 2022; root:xnu-8020.121.3~2/RELEASE_ARM64_T8110 arm64 arm

What steps can reproduce the bug?

export default {
  port: 4281,
  fetch(request) {
    return new Response("Ok");
  }
}

console.log(await fetch("http://localhost:4281/hello"))

How often does it reproduce? Is there a required condition?

No response

What is the expected behavior?

No response

What do you see instead?

The above code fails with the error:

ConnectionRefused: fetch() failed
 path: "http://localhost:4281/hello"

Additional information

No response

Electroid avatar Oct 30 '22 01:10 Electroid

I used to hardcode localhost to 127.0.0.1 as a workaround, but it's not great since technically the OS could have rewritten localhost to anything else

@unetworking do you have any ideas?

Jarred-Sumner avatar Oct 30 '22 01:10 Jarred-Sumner

Fixed in Bun v0.7.1

Jarred-Sumner avatar Jul 31 '23 13:07 Jarred-Sumner

Still have this issue on 0.7.3 for localhost:8000

rubenfiszel avatar Aug 09 '23 08:08 rubenfiszel

On 1.0.0 same error

Voldemat avatar Sep 09 '23 08:09 Voldemat

I have the same error on 1.0.0

Carter-Apas avatar Sep 11 '23 01:09 Carter-Apas

Could this be related with my Next.js dev with bun run --bun next dev? It says there's something regarding sockets, which could be used by Next for HMR, followed by a ConnectionRefused.

dyld[35100]: missing symbol called
ConnectionClosed: The socket connection was closed unexpectedly. For more information, pass `verbose: true` in the second argument to fetch()
 path: "http://localhost:51789/"

ConnectionRefused: Unable to connect. Is the computer able to access the url?
 path: "http://localhost:51789/"

masnormen avatar Sep 12 '23 02:09 masnormen

I have the same issue with the following: wsl2 Ubuntu-22.04 LTS bun-1.0.0 Create nextjs app with : bunx create-next-app test --ts --tailwind --eslint --app --src-dir --use-bun --import-alias "@/*" Run nextjs app with: bun next dev

Gives the output:

$ bun next dev
- ready started server on localhost:3000, url: http://localhost:3000
- event compiled client and server successfully in 209 ms (20 modules)
- wait compiling...
- event compiled client and server successfully in 38 ms (20 modules)
- wait compiling /page (client and server)...
- event compiled client and server successfully in 2.2s (426 modules)
- wait compiling...
- event compiled successfully in 174 ms (235 modules)
ConnectionClosed: The socket connection was closed unexpectedly. For more information, pass `verbose: true` in the second argument to fetch()
 path: "http://localhost:43275/"

- wait compiling /_error (client and server)...
ConnectionRefused: Unable to connect. Is the computer able to access the url?
 path: "http://localhost:43275/favicon.ico"

EDIT 2023-10-09 I gave a try to latest bun version 1.0.4, and it is working fine

BobDenar1212 avatar Sep 12 '23 12:09 BobDenar1212

Using 127.0.0.1 works as a workaround.

markstos avatar Sep 22 '23 01:09 markstos

Edit: this is incorrect, the server will begin on the tick after it has started

the code snippet in the issue is technically wrong.

export default {
  port: 4281,
  fetch(request) {
    return new Response("Ok");
  }
}

console.log(await fetch("http://localhost:4281/hello"))

when you use export default to start a server, it will only start after the module is finished evaluating, so you cannot top-level-await a fetch here.

Bun.serve({
  port: 4281,
  fetch(request) {
    return new Response("Ok");
  },
});

console.log(await fetch("http://localhost:4281"));

This works for me on Linux and MacOS. Can someone test this on WSL?

paperclover avatar Sep 27 '23 11:09 paperclover

I wonder if the issue is that Bun is defaulting to an IPv6 connection for localhost, but there's no entry for localhost for IPv6 in /etc/hosts.

You could try adding this to /etc/hosts if there's not something like it there:

::1             localhost

markstos avatar Sep 27 '23 20:09 markstos

@markstos I already have /etc/hosts entry for IPv6 localhost and unfortunately it still does not work.

kszpakowski avatar Sep 27 '23 21:09 kszpakowski

Having the same issue and can’t really use Bun on any of my projects because of this. Is there something I can do to help debug this?

nCrafts avatar Oct 05 '23 06:10 nCrafts

I think this has been solved with 1.0.4, at least for me. Give it a try

masnormen avatar Oct 05 '23 06:10 masnormen

Unfortunately not for me. It says, ConnectionRefused: Unable to connect. Is the computer able to access the url?

nCrafts avatar Oct 05 '23 07:10 nCrafts

@nCrafts You can checkout the Bun project and review the related test coverage and then add a new failing test which triggers this failure:

https://github.com/oven-sh/bun/blob/main/test/js/web/fetch/fetch.test.ts

There are already some tests for fetch() with localhost, including some with IPv6, so you'll to figure what specifically is triggering this failure.

markstos avatar Oct 06 '23 14:10 markstos

In my case, it seems to happen intermittently when the express res object closes res.on('close', ...)

danny-avila avatar Oct 10 '23 13:10 danny-avila

Related issue on 1.0.11

  • on browser it works all time
  • on bun it works sometimes

  console.log("fetching projects");
  const request = await fetch("https://git.syonet.com/api/v4/projects", {
    headers: {
      "Private-Token": "< my private token >",
    },
  });
  const projects = await request.json();
  console.table(projects);

output:

ConnectionRefused: Unable to connect. Is the computer able to access the url?
 path: "https://git.syonet.com/api/v4/projects"

Schrammel avatar Nov 10 '23 14:11 Schrammel

Same problem on mac m1 cpu.

Took me ages to identify that this line works in Node but not in Bun.

image image

mathiasrw avatar Nov 26 '23 09:11 mathiasrw

I can confirm the problem with bun 0.1.18. But executing the same .js script containing await fetch('http://localhost'... with node works.

prantlf avatar Dec 21 '23 16:12 prantlf

any update?

VigilioYonatan avatar Feb 18 '24 07:02 VigilioYonatan

Still broken on 1.0.27.

Example of node connecting just fine:

$ node
Welcome to Node.js v20.10.0.
Type ".help" for more information.
> const response = await fetch("http://localhost:11434/api/chat")
undefined
> await response.text()
'404 page not found'
>

bun repl equivalent fails with ConnectionRefused: Unable to connect:

$ bun repl
Welcome to Bun v1.0.27
Type ".help" for more information.
[!] Please note that the REPL implementation is still experimental!
    Don't consider it to be representative of the stability or behavior of Bun overall.
> const response = await fetch("http://localhost:11434/api/chat")
ConnectionRefused: Unable to connect. Is the computer able to access the url?
 path: "http://localhost:11434/api/chat"

>
$ bun --version
1.0.27

jameshfisher avatar Feb 19 '24 09:02 jameshfisher

Can confirm replacing localhost with 127.0.0.1 works. Although of course this is not a general workaround

jameshfisher avatar Feb 19 '24 09:02 jameshfisher

Make requests to http://[::1]:3000/ worked for me.

Notes: I'm using Windows, Bun is executing on WSL.

Iuriiiii avatar Feb 21 '24 21:02 Iuriiiii

Can confirm that I have the same error when trying to accessing a local running nest application with hostname 0.0.0.0 I have two possibilities here to solve this:

Either remove the hostname in the nest appliction OR use 127.0.0.1 instead of localhost when making the fetch from bun

my hosts file has also nothing suspicious in it and it should be able to resolve localhost correctly on my machine

127.0.0.1	localhost
255.255.255.255	broadcasthost
::1             localhost

zartinn avatar Feb 25 '24 14:02 zartinn

I found a solution temporarily. Install ngrok https://dashboard.ngrok.com/get-started/setup/windows , login in ngrok and CMD EXECUTE "ngork.exe http 3000" you will have a host https temporarily

VigilioYonatan avatar Feb 26 '24 06:02 VigilioYonatan

same error with arbitrary ip addresses in bun 1.0.29

kirill-dev-pro avatar Mar 01 '24 19:03 kirill-dev-pro

@kirill-dev-pro Example please?

mathiasrw avatar Mar 03 '24 08:03 mathiasrw

This reminds me about ECONNREFUSED errors, which started occurring when Node.js 18 was released. They were caused by a change in the Node.js implementation, preferring IPV6 to IPV4 in the address resolution. (Actually, it had happened in Node.js 17 already, but most of the community had waited for LTS versions as usual.) npm install started failing. Packages like puppeteer, which download a part from other servers than npmjs.org, couldn't be installed. There're many bug reports related to it like this one.

An easy way of reproducing the problem was making a server listen at 127.0.0.1:80 or 0.0.0.0:80, which is very often, and connecting to [::1]:80, which failed. The IPV6 address was the new result of the resolution of http://localhost.

It took some time to fix the IPV6 configuration on servers and clients. I had to survive with the environment variable NODE_OPTIONS=--dns-result-order=ipv4first for quite some time. But a year has passed, puppeteer and storybook can be installed on both IPV4 and IPV6 networks today and people forgot about the dark period.

You can feel a deajvu by making a mistake deliberately:

export default {
  port: 4281,
  hostname: '127.0.0.1', // 0.0.0.0 is bad too
  fetch(request) {
    return new Response("Ok");
  }
}

console.log(await fetch("http://[::1]:4281/hello"))

If you don't specify any value for hostname, Bun will do something magical and connections using both IPV4 and IPV6 will succeed:

const server = Bun.serve({
  port: 4281,
  fetch(request) {
    return new Response("Welcome to Bun!");
  }
})

console.log(await fetch("http://127.0.0.1:4281/hello"))
console.log(await fetch("http://[::1]:4281/hello"))

As sool as you specify hostname, the server will listen to only one IP address type, according to the local configuration of localhost. Shouldn't Bun listen to both IPV4 and IPV6 addresses on dual-stack systems?

prantlf avatar Mar 03 '24 11:03 prantlf

Still having this issue on bun 1.0.30

oSethoum avatar Mar 13 '24 22:03 oSethoum

Still happening on 1.0.33.

didier avatar Mar 21 '24 11:03 didier