Hello everyone, I have a question. I'm using the example from the official website to build an Endpoint in my own project, and it's located at src/pages/api/[id].json.ts. It looks like this:
import type { APIRoute } from 'astro'
const usernames = ['Sarah', 'Chris', 'Dan']
export const get: APIRoute = ({ params, request }) => {
const id = params.id
return {
body: JSON.stringify({
name: usernames[id],
}),
}
}
export function getStaticPaths() {
return [
{ params: { id: '0' } },
{ params: { id: '1' } },
{ params: { id: '2' } },
]
}
Later, I want to use the JSON file generated by this Endpoint at my project's root domain, for example, I want to use /api/1.json generated by it. So I used fetch to request it in src/pages/index.astro, like this:
---
const res = await fetch('/api/1.json') // ❌ This will result in an error: `Failed to parse URL from /api/1.json`
const res = await fetch('http://localhost:8001/api/1.json') // ✅ This will result in a successful request.
---
I need to deploy it to Netlify or other platforms after development, and the root domain will change. So I think I should use relative paths to request in 'fetch'. However, using a relative path like in the example above will result in an error. Has anyone found any errors in my code? I hope someone can help me solve this problem. Thank you 🥰 .