Problem with my api route

I created a dummy login api route under 'routes/api/login.ts' and when I call fetch on the url like so:
fetch("/api/login")
fetch("/api/login")
it fails because that's an 'invalid route'
3 Replies
MaDsEn
MaDsEn4w ago
How have you setup the login.ts?
TheOneThatPlaysTooMuch
Hi! I actually found out why it doesn't work but I still don't know why its like this: when I fetch a full url like "https://google.com" its fine, but when I fetch a relative url like "/api/login" called from a server component, it says it is an invalid url, but when I call it from an island component, its fine.
marvinh.
marvinh.4w ago
When you call fetch without an origin and only a pathname like /api/login you're unconsciously making the assumption that the fetch call would insert the origin. This works in browsers because there only ever is one origin per execution context (=tab or iframe). This is not the case on the server. A single Deno process can spawn multiple servers at different addresses. There is no way to know which origin should be injected.
const serverA = Deno.serve(
{ port: 3000, hostname: "127.0.0.1" },
(_req) => new Response("Server A")
);

const serverB = Deno.serve(
{ port: 5000, hostname: "127.0.0.1" },
(_req) => new Response("Server B")
);

// How should Deno know which server the fetch
// should fetch from? Should it fetch from
// Server A or B? It's impossible to know.
fetch("/foo")
const serverA = Deno.serve(
{ port: 3000, hostname: "127.0.0.1" },
(_req) => new Response("Server A")
);

const serverB = Deno.serve(
{ port: 5000, hostname: "127.0.0.1" },
(_req) => new Response("Server B")
);

// How should Deno know which server the fetch
// should fetch from? Should it fetch from
// Server A or B? It's impossible to know.
fetch("/foo")
For that reason you always need to specify a full URL.

Did you find this page helpful?