Cloudflare KV 命名空间未绑定

Cac*_*nly 5 javascript cloudflare typescript cloudflare-workers

Ranwrangler dev似乎没有绑定 Worker KV:

ERROR in /src/handler.ts
./src/handler.ts 16:8-17
[tsl] ERROR in /src/handler.ts(16,9)
      TS2304: Cannot find name 'generalKV'.
Run Code Online (Sandbox Code Playgroud)

这是handler.ts

async function postHandler(request: Request): Promise<Response> {
  let content = JSON.stringify(await request.json());
  await generalKV.put([Date.now().toString()], JSON.stringify(content));
  return new Response(content);
}
Run Code Online (Sandbox Code Playgroud)

wrangler.toml:

name = "general-assignment"
type = "javascript"
account_id = "<id>"
workers_dev = true
compatibility_date = "2021-11-01"
kv_namespaces = [ 
    { binding = "generalKV", id = "<id>", preview_id = "<id>" }
]
Run Code Online (Sandbox Code Playgroud)

有人建议更改kv_namespaceskv-namespaces,但这对我不起作用。如果我错过了任何其他内容,请告诉我。

Dra*_*kes 14

对于通过 Google 提出此问题并使用 Wrangler v2 并收到此错误的读者:

未捕获(承诺中)ReferenceError:MY_KV 未定义

教程和示例忽略了第二个参数(和第三个参数)。第二个参数保存环境kv您可以通过以下步骤使用和绑定:

# Create the KV namespaces
wrangler kv:namespace create "MY_KV" &&\
wrangler kv:namespace create "MY_KV" --preview
Run Code Online (Sandbox Code Playgroud)

wrangler如果没有预览 KV,则会抱怨,因此请创建它们。接下来,创建一个数组条目并在默认(dev)部分中kv_namespaces复制(如下所示)。preview_idyyyy

# wrangler.toml
name = "worker"
main = "src/index.js"
compatibility_date = "2022-04-14"
account_id = "...."
workers_dev = true

routes = [
    "exmample.com/*"
]

# Duplicate preview_id to id
kv_namespaces = [
    { binding = "MY_KV", preview_id = "yyyy", id = "yyyy" }
]

# Run `wrangler publish --env production` when happy
[env.production]
kv_namespaces = [
    { binding = "MY_KV", id = "xxxx" }
]
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样绑定到 kv :

# index.js
export default {
  async fetch(request, env) {
  ...
  const someKV = env.MY_KV.get("some-key");
  ...
  }
Run Code Online (Sandbox Code Playgroud)

  • @Mecanik 被困了这么久,非常感谢,哈哈,这是预览 ID (2认同)