How to fetch an endpoint in another endpoint?

Viewed 247

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)?

2 Answers

I think it would be better to wrap the main logic of the /api/metadata endpoint into its own module, then import that module in both endpoints. So your code would look like this (in both endpoints):

import { getMetadata } from '$lib/metadata.js'


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

        // const body = await res.json()

        const body = getMetadata();


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

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')
Related