addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));
async function handleRequest(event) {
// Get the client request.
let req = event.request;
let url = new URL(req.url);
// Option 1: detect trailing slash and trigger client side redirect
// From the client prespective, this means a request ending in a
// slash will elicit a redirect response.
if(url.pathname.endsWith('/')){
return new Response(null, {
status: 301,
headers: new Headers({ "Location": url.pathname.slice(0,-1), }),
});
}
// Option 2: remove the trailing slash from the request
// From the client prespective, this means the request works whether
// or not it ends in a slash...(Coment Option 1 to test this one)
if(url.pathname.endsWith('/')){
url.pathname = url.pathname.slice(0,-1);
}
// Send the request to `origin_0`.
const backendResponse = fetch(req, {
backend: "origin_0"
});
// Send the backend response back to the client.
return backendResponse;
}