Node fetch to replica connection refused

I want to perform http requests into my local canister. With curl from the command line everything works just fine:

curl http://bkyz2-fmaaa-aaaaa-qaaaq-cai.localhost:8000/res-send

When I try to do the same request in node it fails saying that the connection was refused:

const response = await fetch(
    `http://bkyz2-fmaaa-aaaaa-qaaaq-cai.localhost:8000/res-send`
);

Does the proxy refuse certain user agents or something?

This code works fine from a web browser running on localhost:

fetch('http://bkyz2-fmaaa-aaaaa-qaaaq-cai.localhost:8000/res-send').then((response) => response.text()).then((final) => console.log(final)).catch((error) => console.log(error))

Ah, okay so in newer versions of node DNS resolution for localhost is favoring ipv6 which apparently the ICP replica does not support.

See here: http - ECONNREFUSED when making a request to localhost using fetch in Node.js - Stack Overflow

This fixed it for me:

import * as dns from 'node:dns';
dns.setDefaultResultOrder('ipv4first');
1 Like