Search code examples
javascriptsveltekit

How to fetch an endpoint in another endpoint?


I have an endpoint in /api/metadata, and I want to fetch it in another endpoint like this:

export const get: RequestHandler = async (event) => {
    try {
        const res = await fetch(event.url + '/api/metadata')

        const body = await res.json()

        return {
            body
        };
    } catch (error) {
        console.error(error);
        return {
            status: 500
        };
    }
};

But I got the following error:

FetchError: request to http://localhost:3000/sitemap.xml/api/metadata failed, reason: connect ECONNREFUSED ::1:3000

When I change the fetch location to http://0.0.0.0:3000/api/metadata the fetch would just work. Is it possible for me to handle this fetch request correctly without using conditional with process.env.NODE_ENV(the dev in $app/env)?


Solution

  • The event.url contains full URL (with pathname, query string, etc.).

    Try to use event.url.origin:

    const res = await fetch(event.url.origin + '/api/metadata')