代码之家  ›  专栏  ›  技术社区  ›  scouech

在Cloudflare Workers上访问Hono JS上下文中的FetchEvent时出现问题

  •  0
  • scouech  · 技术社区  · 2 年前

    我正在使用Hono JS开发Cloudflare Workers应用程序,遇到无法访问的问题 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类似的问题,或者可以指出我的实现可能出了什么问题?

    如有任何见解或建议,我们将不胜感激!

    0 回复  |  直到 2 年前
        1
  •  0
  •   Kian    2 年前

    您正在使用 Module Workers ( export default ),而不是服务人员,所以没有更多 addEventListener 或事件。

    你会有 c.req , c.env c.executionCtx 相反

    c.req Request 对象等效于 event.request .

    c.env 包含绑定,这些绑定不再是全局绑定,而是在 env 对象

    c.执行Ctx 包含 waitUntil() passThroughOnException() 这些方法等效于 event 对象

    看看Hono的 Cloudflare Workers guide Context API reference .