Cloudflare Worker刷新页面,如果错误520



我们在共享主机上运行暂存环境。我们偶尔会遇到未知错误的麻烦。当页面加载时,Cloudflare会显示520错误。

这不是资源问题,我们没有服务器访问权限。它真的不经常发生,所以我想运行一个Cloudflare Worker,如果有520错误刷新页面。

有人知道怎么写这个吗?

应该像下面这样做。注意,这不会"刷新"。该页面。相反,错误页面永远不会到达用户的浏览器,因为在发生错误时,整个请求被重试,重试响应被发送到浏览器。

当然,最好弄清楚错误发生的原因。Cloudflare的520错误意味着您的源服务器正在向Cloudflare返回无效响应。这里有一页讨论如何解决这个问题。

也就是说,当问题正在调查时,Worker可以提供一种方便的方法来"把问题扫到地毯下面"。让你的访问者可以毫无问题地访问你的网站。

export default {
async fetch(request, env, ctx) {
if (request.body) {
// This request has a body, i.e. it's submitting some information to
// the server, not just requesting a web page. If we wanted to be able
// to retry such requests, we'd have to buffer the body so that we
// can send it twice. That is expensive, so instead we'll just hope
// that these requests (which are relatively uncommon) don't fail.
// So we just pass the request to the server and return the response
// nomally.
return fetch(request);
}
// Try the request the first time.
let response = await fetch(request);
if (response.status == 520) {
// The server returned status 520. Let's retry the request. But
// we'll only retry once, since we don't want to get stuck in an
// infinite retry loop.
// Let's discard the previous response body. This is not strictly
// required but it helps let the Workers Runtime know that it doesn't
// need to hold open the HTTP connection for the failed request.
await response.arrayBuffer();
// OK, now we retry the request, and replace the response with the
// new version.
response = await fetch(request);
}
return response;
}
}

相关内容

最新更新