MaxCore
MaxCore

Reputation: 2738

SvelteKit's how to omit host address in fetch url under proxy

I've configured proxy, so http://localhost:3000/api/articles goes to http://127.0.0.1:8000/articles

svelte.config.js:

const config = {
    kit: {
        target: '#svelte',
        vite: {
            server: {
                proxy: {
                    '/api': {
                        target: 'http://127.0.0.1:8000',
                        rewrite: (path) => path.replace(/^\/api/, ''),
                        changeOrigin: true,
                    }
                }
            }
        }
    }
};

And requests like this works just fine:

<script context="module">
    export const load = async ({ fetch }) => {
        const res = await fetch('http://localhost:3000/api/articles');
        ...
    }
</script>

But they do not work if host is omitted:

<script context="module">
    export const load = async ({ fetch }) => {
        const res = await fetch('/api/articles');
        ...
    }
</script>

res contains 404 error

Playing with https://kit.svelte.dev/docs#configuration-host did not help

So, is it possible to omit host in load's fetch under proxy?

Upvotes: 3

Views: 1389

Answers (1)

Andr&#233;
Andr&#233;

Reputation: 36

Thank you for sharing your vite configuration. I'm using @sveltejs/[email protected], which runs in dev mode on Port 5173 and i am runnig an http-server on port 8080, which simply responses »Good morning, world!«.

// vite.config.ts
import { sveltekit } from '@sveltejs/kit/vite';
import type { UserConfig } from 'vite';

const config: UserConfig = {
    plugins: [sveltekit()],
    server: {
        proxy: {
            '/api': {
                target: 'http://[::1]:8080',
                rewrite: (path) => path.replace(/^\/api/, ''),
                changeOrigin: true
            }
        }
    }
};

export default config;
// src/routes/hello/+page.svelte
<script lang="ts">
    const hi = fetch('/api').then((x) => x.text());
</script>

{#await hi}
    <p>Loading ...</p>
{:then data}
    <p>Greeting: {data}</p>
{:catch error}
    <p>Error {error.message}</p>
{/await}

On http://127.0.0.1:5173/hello my browser renders first Loading ... and then settles to Greeting: Good morning, world!.

Upvotes: 2

Related Questions