javascript - Cloudflare worker 用于重定向、无限循环
问题描述
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);
}
}
我想将用户重定向到 response.destination url,但它经常将用户重定向到,所以它崩溃了。我认为从 mongo 获取数据时会触发 fetch eventlistener,但我找不到其他方法来执行此操作示例链接: 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)}
}
解决方案
相信剩下的问题是最后几行正在使用response.destination
而不是result.destination
. 我用以下方法启动了一个新工人,并且能够在没有路径的情况下成功测试,并且您的路径为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);
}
}
尝试尝试一下,也许在新的工作人员/ URL 上以避免任何可能的缓存问题?
推荐阅读
- flutter - 如何在轮播滑块颤动中设置图像大小
- php - 如何使用 Cordova 和 PHP 后端(无 FireBase)实现 Apple SignIn
- git - 如何在特定版本中查看 Github 存储库中的代码?
- python - 如何找到将 X、Y、Z 向量与另一个坐标系对齐的角度
- r - 使用 ggsurvplot 中的 facet.by 时无法绘制 p 值。错误消息:“可变长度不同”
- android - Visual Studio 2019、Android 和 CMake
- xapi - Learning Locker xAPI 在发送有效凭据的语句时返回未经授权的消息
- icons - 在 SwiftUI 中使用系统图标和 macOS 作为按钮
- c - 如何编写一个输入一个单词并计算该单词在 C 中给定字符串中出现的次数的程序?
- c++ - 并发程序不终止