sveltejs / sapper

The next small thing in web development, powered by Svelte
https://sapper.svelte.dev
MIT License
6.99k stars 433 forks source link

Connect ECONNREFUSED 127.0.0.1:80 #1671

Closed kinton closed 3 years ago

kinton commented 3 years ago

Hello!

I am developing my pet project using sapper + rails api + nginx + docker under compose.

I created an architecture when / location directs to sapper and /api location directs to rails. I can open http://localhost/api/items page and get my items. Moreover, it works when used in onMount function. But when I trying to preload the data (to achieve SSR) by this code

<script context="module">
    export async function preload(page, session) {

        let res = await this.fetch(`${process.env.API_URL}/api/items`);  // process.env.API_URL is "http://localhost", but other variants like "//127.0.0.1:80" also fails
        let ans = await res.json();
        let items = ans.items;

        return { items };
    }
</script>

I am getting an error: request to http://localhost/api/items failed, reason: connect ECONNREFUSED 127.0.0.1:80

Can you please explain what am I doing wrong?

Conduitry commented 3 years ago

That will only work if the API is visible inside the container at localhost:80. From what you said, I can't tell whether it is. Probably not if it's in a different container.

GitHub issues aren't the right place for support questions like this. Please ask on StackOverflow or in our Discord chat room. And please have a more complete reproduction so people don't have to guess what your Docker setup looks like.

kinton commented 3 years ago

@Conduitry

Thanks for the quick response! My friend asked about this problem on the Sapper thematic forum, but they came to the conclusion that the problem might be in this.fetch, so I decided to ask you. In general, I had thoughts about the architecture of containers, after your answer I looked again and found an error.

If someone with a similar problem will find this page, then you can do something like this:

let res = await this.fetch(
    `${process.browser ? process.env.API_URL : process.env.API_URL_CONTAINER}
    /api/items`);

Where, in my case, API_URL=http://localhost and API_URL_CONTAINER=http://server:3001.