Cloudflare worker 中的环境变量使用 node.js
environment variable use in Cloudflare workers node.js
我看到很多文章在Cloudflare workers中设置环境变量。但我无法在 node.js 中读取或检索它
代码:
`async function handleRequest(request) {
if ('OKOK' == process.env.API_KEY) {
return new Response('found', {
headers: { 'content-type': 'text/plain' },
})
}
}
`
wrangler.toml
name = "hello"
type = "javascript"
# account_id = ""
workers_dev = true
[env.production]
name = "API_KEY"
Cloudflare Workers 不使用 Node.js。在 Workers 中,环境变量变成了简单的全局变量。因此,要访问您的环境变量,您只需编写 API_KEY
,而不是 process.env.API_KEY
。
(注意:Workers 目前正在过渡到基于 ES 模块的新语法。在该语法中,环境变量的工作方式不同;一个 env
对象被传递给包含所有变量的事件处理程序。大多数人都不是不过,现在还没有使用这个新语法。如果您的 JavaScript 使用 export default {
来定义事件处理程序,您就会知道您是否正在使用它;另一方面,如果它使用 addEventListener("fetch", ...)
,然后它使用旧语法。)
我建议你现在使用 Miniflare,非常简单和强大
"start": "miniflare --watch --debug -e .env"
顺便说一下,这是一个官方的 Cloudflare 库:
https://www.npmjs.com/package/miniflare
原因:
Miniflare 是用于开发和测试 Cloudflare Workers 的模拟器。
Fun: develop workers easily with detailed logging, file watching
and pretty error pages supporting source maps.
Full-featured: supports most Workers features, including KV,
Durable Objects, WebSockets, modules and more.
⚡ Fully-local: test and develop Workers without an internet
connection. Reload code on change quickly. It's an alternative to
wrangler dev, written in TypeScript, that runs your workers in a
sandbox implementing Workers' runtime APIs.
我看到很多文章在Cloudflare workers中设置环境变量。但我无法在 node.js 中读取或检索它 代码:
`async function handleRequest(request) {
if ('OKOK' == process.env.API_KEY) {
return new Response('found', {
headers: { 'content-type': 'text/plain' },
})
}
}
`
wrangler.toml
name = "hello"
type = "javascript"
# account_id = ""
workers_dev = true
[env.production]
name = "API_KEY"
Cloudflare Workers 不使用 Node.js。在 Workers 中,环境变量变成了简单的全局变量。因此,要访问您的环境变量,您只需编写 API_KEY
,而不是 process.env.API_KEY
。
(注意:Workers 目前正在过渡到基于 ES 模块的新语法。在该语法中,环境变量的工作方式不同;一个 env
对象被传递给包含所有变量的事件处理程序。大多数人都不是不过,现在还没有使用这个新语法。如果您的 JavaScript 使用 export default {
来定义事件处理程序,您就会知道您是否正在使用它;另一方面,如果它使用 addEventListener("fetch", ...)
,然后它使用旧语法。)
我建议你现在使用 Miniflare,非常简单和强大
"start": "miniflare --watch --debug -e .env"
顺便说一下,这是一个官方的 Cloudflare 库: https://www.npmjs.com/package/miniflare
原因: Miniflare 是用于开发和测试 Cloudflare Workers 的模拟器。
Fun: develop workers easily with detailed logging, file watching and pretty error pages supporting source maps.
Full-featured: supports most Workers features, including KV, Durable Objects, WebSockets, modules and more.
⚡ Fully-local: test and develop Workers without an internet connection. Reload code on change quickly. It's an alternative to wrangler dev, written in TypeScript, that runs your workers in a sandbox implementing Workers' runtime APIs.