gpt4 book ai didi

javascript - 在 fetchEvent 中返回请求作为响应

转载 作者:行者123 更新时间:2023-11-29 23:22:17 25 4
gpt4 key购买 nike

在服务 worker 内部,如果请求失败,我会尝试返回发出的请求作为响应。看似很简单,但行不通。

事实上,当我尝试返回它时,它返回一个空对象,即使使用 .clone() 也是如此。

代码如下:

fetch(event.request.clone())
.catch((err) => {
queue.addRequest(event.request)
return new Response(JSON.stringify({ deferred: true, ...event.request }), {
headers: new Headers({ "Content-Type": "application/json" })
})
})

它的响应总是:{ deferred: true }。没有别的。

有可能吗?

最佳答案

我刚刚找到获取请求正文并将其返回到我的案例中的方法。

可以使用 .json() 返回请求正文中的 promise 。

看起来像这样:

fetch(event.request.clone())
.catch((err) => {
queue.addRequest(event.request)
return event.request.clone().json().then((requestBody) => {
return new Response(JSON.stringify({ deferred: true, ...requestBody }), {
headers: new Headers({ "Content-Type": "application/json" })
})
})
})

关于javascript - 在 fetchEvent 中返回请求作为响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50252519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com