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

部署至Cloudflare Pages后Nuxt 3 API路由无法访问Cloudflare D1数据库

Nuxt 3部署Cloudflare Pages后无法访问D1数据库绑定

问题背景

  • 项目基于Nuxt 3构建,通过GitHub集成部署至Cloudflare Pages
  • 已在Cloudflare控制台为Pages项目配置D1数据库绑定,绑定变量名为DB
  • 部署完成后,在API路由中尝试访问该绑定时失败,抛出错误:Database connection is not configured.
  • 本地开发环境可正常访问数据库:已安装wrangler及nitro-cloudflare-dev模块,且配置了wrangler.toml文件

相关代码

API路由文件(/server/api/database.js)

export default defineEventHandler(async (event) => {
  try {
    // 尝试访问数据库
    const db = event.context.cloudflare.env.DB;

    if (!db) {
      throw new Error('Database connection is not configured.');
    }

    // 后续数据库操作...
  } catch (error) {
    // 错误处理...
  }
});

wrangler.toml配置

[[d1_databases]]
binding = "DB"
database_name = "prod-example"
database_id = "813210b5-f217-4eaa-ae5d-xxxxxxxxxxxx"
preview_database_id = "DB"

已查阅内容

  • Cloudflare Pages部署Nuxt站点指南中关于应用绑定的说明
  • Cloudflare Pages函数绑定中D1数据库的相关内容
  • D1本地开发指南中Pages本地开发的部分

目前未找到Nuxt on Pages场景下访问D1绑定的明确、统一的环境变量访问方式,求问如何正确在部署后的Nuxt API路由中访问Cloudflare Pages的D1绑定?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 18:33:20