Worker Routes not working

I'm trying to create an URL shorter using Cloudflare Worker. However, when I try to access the URL, the Worker does not forward to other site, it just display my not found page. For instance, https://hoaq.id.vn/s/skin will forward to https://drive.google.com/file/d/1BokisPpuP9fQlkaupkdwlUacDQMLDTMy/view?usp=drive_link Here is the code
export default {
async fetch(request, env) {
return await handleRequest(request, env).catch(
(err) => new Response(err.stack, { status: 500 })
)
}
}

async function handleRequest(request, env) {
const url = new URL(request.url);
const pathname = url.pathname.substring(2).replace(/^\/|\/$/g, "");
const location = await env.LINKS.get(pathname);

if (location) {
return Response.redirect(location, 301);
}

return fetch(request);
}
export default {
async fetch(request, env) {
return await handleRequest(request, env).catch(
(err) => new Response(err.stack, { status: 500 })
)
}
}

async function handleRequest(request, env) {
const url = new URL(request.url);
const pathname = url.pathname.substring(2).replace(/^\/|\/$/g, "");
const location = await env.LINKS.get(pathname);

if (location) {
return Response.redirect(location, 301);
}

return fetch(request);
}
No description
5 Replies
Dullaz
Dullaz5mo ago
What does ‘fetch(request)’ do? Huh? It loops back into the first method? I built a url shortener on cf workers using nextjs, and it works so this is definitely possible. that being said, i dont understand why handleRequest returns fetch(request) if location is not found. might be better to keep it all in one function and refactor after it starts working.
Walshy
Walshy5mo ago
fetch(request) will go into origin (well what is behind the worker) seems like that might be what's happening here
Dullaz
Dullaz5mo ago
Fetch -> handleRequest. handleRequest -> fetch? Am I missing something or is this a weird loop?
Walshy
Walshy5mo ago
to fire the fetch function it'd be this.fetch, the fetch there is the fetch api - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API not a loop, just passing through to origin if the link is not found
mune
mune5mo ago
indeed
Want results from more Discord servers?
Add your server