addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
var pathname = url.pathname.substring(1, url.pathname.length)
var response = await fetch('https://eu-central-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/1saas-functions-mmlow/service/urlRedirect/incoming_webhook/cloudWorker', {
headers: {
"Accept": "application/json",
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({identifier: pathname}),
})
const result = await response.json();
if(response.destination) {
return Response.redirect(response.destination, 302);
} else {
return Response.redirect("https://1saas.co", 302);
}
}
I want to redirect the user to the response.destination url but it redirects the user to often so it crashes. I think the fetch eventlistener gets triggered when fetching data from mongo, but i cant find a other way to do it example link: http://lyl.ai/6j6P6Zwr
addEventListener('fetch', event => {
try{event.respondWith(handleRequest(event.request))} catch(e){console.log(e)}
})
async function handleRequest(request){
try{
const url = new URL(request.url)
var pathname = url.pathname.substring(1, url.pathname.length)
/*var response = await fetch('https://eu-central-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/1saas-functions-mmlow/service/urlRedirect/incoming_webhook/cloudWorker', {
headers: {
"Accept": "application/json",
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({identifier: pathname}),
})*/
if(true){
return Response.redirect("https://1saas.co", 302);
} else {
return Response.redirect("https://1saas.co", 302);
}
}catch(e)
{console.log(e.message)}
}
Believe the remaining issue is that the last couple of lines are using response.destination instead of result.destination. I spun up a new worker with the following, and was able to succesfully test with no path, and with your path of 6j6P6Zwr -
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
var pathname = url.pathname.substring(1, url.pathname.length)
var response = await fetch('https://eu-central-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/1saas-functions-mmlow/service/urlRedirect/incoming_webhook/cloudWorker', {
headers: {
"Accept": "application/json",
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({identifier: pathname}),
})
const result = await response.json();
if(result.destination) {
return Response.redirect(result.destination, 302);
} else {
return Response.redirect("https://1saas.co", 302);
}
}
Try giving this a shot, maybe on a new worker / URL to avoid any possible caching issues?