You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cloudflare Workers Node.js环境下无法读取配置的环境变量如何解决

无法读取环境变量的原因
  • wrangler.toml配置格式错误:你当前配置中[env.production]下的name字段是用于定义production环境下的Worker部署名称,不是环境变量配置项。环境变量需要写在对应环境的[vars]配置块下,键值对形式定义。
  • Cloudflare Workers运行时不支持process.env:Workers运行环境不是标准Node.js,环境变量不会挂载到process.env对象上,而是通过Worker入口函数的第二个env参数注入。
解决方法
  1. 修正wrangler.toml配置,按照如下格式定义环境变量:
name = "hello"
type = "javascript"

# account_id = ""
workers_dev = true

# 所有环境通用的环境变量写在全局[vars]下
[vars]
API_KEY = "OKOK"

# 如果需要为production环境单独配置变量,写在[env.production.vars]下
# [env.production.vars]
# API_KEY = "生产环境专属密钥"

如果你是直接在Cloudflare面板手动添加的环境变量,不需要在wrangler.toml重复定义,部署时注意不要开启覆盖面板变量的选项即可。

  1. 调整代码逻辑,从env参数读取环境变量:
// 入口函数固定结构,第二个参数env存储所有环境变量
export default {
  async fetch(request, env, ctx) {
    return handleRequest(request, env);
  }
};

async function handleRequest(request, env) {
  if ('OKOK' == env.API_KEY) {
    return new Response('found', {
      headers: { 'content-type': 'text/plain' },
    })
  }
  // 注意补全其他分支的返回值,避免Worker报错
  return new Response('not match', {
    status: 403,
    headers: { 'content-type': 'text/plain' }
  })
}

内容的提问来源于stack exchange,提问作者Noobdeveloper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 03:15:03