我正在使用 Hono JS 开发 Cloudflare Workers 应用程序,但遇到了无法在 Hono 上下文中访问
FetchEvent
的问题。该应用程序在 itty 路由器和默认的 Cloudflare 工作设置中运行良好,但在 Hono 中,我遇到了困难。
这是我的
index.js
的片段:
const app = new Hono();
app.get('/backgroundsounds', async (c) => {
const event = c.event
console.log("Event is", event);
return await handleBackgroundSoundsGetAll(c);
});
export default app;
这是我的
handleBackgroundSoundsGetAll
功能:
export const handleBackgroundSoundsGetAll = async (c) => {
const { MY_BUCKET } = c.env;
const request = c.req; // Access the request from the Hono context
const cacheUrl = new URL(request.url);
const cacheKey = new Request(cacheUrl.toString(), { method: 'GET' });
const cache = caches.default;
const fileName = "backgroundsounds.json";
console.log("Checking cache for key", cacheKey);
let response = await cache.match(cacheKey);
console.log("Cache match result", response);
// Access R2 bucket from environment bindings
const backgroundSoundsJson = c.env.MY_BUCKET.get(fileName);
console.log("Fetching object and ETag from R2 bucket in the background");
if (response) {
console.log("Cache hit, serving response");
if (c.event) {
c.event.waitUntil(...)
}
return response;
} else {
// Additional handling for cache miss
}
};
我收到错误消息:
This context has no FetchEvent
。我不确定我错过了什么或做错了什么。当我使用 itty 路由器或标准 Cloudflare 工作设置时,相同的逻辑有效。
有没有人在 Cloudflare Workers 上遇到过与 Hono 类似的问题,或者可以指出我的实施中可能出现的问题吗?
任何见解或建议将不胜感激!
您使用的是 Module Workers (
export default
),而不是 Service Workers,因此不再有 addEventListener
或事件。
您将拥有
c.req
、c.env
和 c.executionCtx
。
c.req
是一个 Request
对象,相当于 event.request
。
c.env
包含您的绑定,它们不再是全局变量,而是位于 env
对象上。
c.executionCtx
包含 waitUntil()
和 passThroughOnException()
,它们相当于 event
对象上的方法。
查看 Hono 的 Cloudflare Workers 指南 和 Context API 参考。