在服务 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/