如何在cloudflare工作人员中使用KV?

问题描述 投票:0回答:1

我使用的是wrangler v3.78。我正在尝试制作一个测试工作人员,只是为了弄清楚 KV 数据库是如何工作的。这是我的代码:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const { pathname } = new URL(request.url)

  if (request.method === 'GET' && pathname === '/retrieve') {
    const key = 'data'
    const data = await env.BINDING_NAME.get(key, 'text')
    return new Response(data || 'Key not found', { status: 200 })
  } else if (request.method === 'POST' && pathname === '/store') {
    const data = await request.text()
    await env.BINDING_NAME.put('data', data)
    return new Response('Data stored successfully', { status: 200 })
  } else {
    return new Response(JSON.stringify({ error: 404, message: 'Not found' }), {
      status: 404,
      headers: { 'Content-Type': 'application/json' },
    })
  }
}

当我运行

wrangler dev
npm run dev
时,我收到以下错误:

X [ERROR] service core:user:api: Uncaught Error: Dynamic require of "node:stream" is not supported

    at null.<anonymous> (core:user:api:9:11)
    at null.<anonymous> (core:user:api:107:28)
    at null.<anonymous> (core:user:api:1222:3)


X [ERROR] MiniflareCoreError [ERR_RUNTIME_FAILURE]: The Workers runtime failed to start. There is likely additional logging output above.

任何有关我做错了什么导致这些错误以及如何修复它们的帮助将非常感谢,谢谢。 我对任何后端开发都很陌生,而且我真的不明白其中一些代码的作用,所以我很有可能弄错了。 还是谢谢啦

javascript cloudflare cloudflare-workers wrangler cloudflare-kv
1个回答
0
投票

这里的问题之一可能与旧语法有关。 Cloudflare 建议将

addEventListener('fetch', ...)
替换为
async fetch
,如 此处所述

此外,GitHub 中关于此的主线程:https://github.com/cloudflare/workerd/issues/854

固定版本应该看起来像这样(不幸的是我没有能力测试它):

export default {
  async fetch(request, env) {
    const { pathname } = new URL(request.url);

    if (request.method === 'GET' && pathname === '/retrieve') {
      const key = 'data';
      const data = await env.BINDING_NAME.get(key, 'text');
      return new Response(data || 'Key not found', { status: 200 });
    } else if (request.method === 'POST' && pathname === '/store') {
      const data = await request.text();
      await env.BINDING_NAME.put('data', data);
      return new Response('Data stored successfully', { status: 200 });
    } else {
      return new Response(JSON.stringify({ error: 404, message: 'Not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' },
      });
    }
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.