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

await函数中变量未注册:Notion API调用变量显示undefined

问题分析与解决

你的变量显示undefined和作用域无关,核心是前端请求未正确传递请求体,以及Notion API参数格式不符合规范,以下是具体修复步骤:

1. 修复前端Fetch请求

你的前端代码只传了headers,既没指定POST方法(默认GET请求无body),也没发送请求体数据,修改如下:

const bodyQuery = {
  companyName: "Example",
  email: "example@gmail.com",
  // 补充其他参数
};

try {
  await fetch("/api/v1/submit", {
    method: "POST", // 必须指定POST,GET无法携带请求体
    headers: {
      "Content-Type": "application/json", // 声明请求体为JSON格式
      // 保留你的其他headers配置
    },
    body: JSON.stringify(bodyQuery), // 将对象转为JSON字符串传递
  })
  .then((res) => res.json())
  .then((res) => setTests(res));
} catch (e) {
  console.log("e:", e);
}

2. 修正后端Notion API调用格式

Notion的pages.create不支持直接传入自定义字段,必须严格按照API规范,在properties中匹配数据库的属性类型和名称:

export default async function handler(req, res) {
  // 先打印调试,确认是否接收到前端数据
  console.log("接收到的请求体:", req.body);

  const { companyName, email, panelNames, tags, markers, inquiry } = req.body;

  try {
    const result = await notion.pages.create({
      parent: {
        database_id: "你的Notion数据库ID", // 必填:指定要添加数据的数据库ID
      },
      properties: {
        // 键名必须和你Notion数据库的属性名称完全一致
        "公司名称": { // 假设数据库中是「标题」类型属性
          title: [
            { text: { content: companyName || "" } }
          ]
        },
        "邮箱": { // 假设数据库中是「邮箱」类型属性
          email: email || ""
        },
        // 其他字段根据对应属性类型配置,比如多选、文本等
      }
    });

    res.status(200).json({ success: true, data: result });
  } catch (e) {
    console.error("Notion API调用错误:", e);
    res.status(500).json({ success: false, error: e.message });
  }
}

额外调试建议

  • 如果后端打印req.body仍为undefined,检查框架的body解析配置:比如Express需要添加express.json()中间件,Next.js则默认支持JSON请求体。
  • 确认Notion API Token拥有目标数据库的编辑权限,数据库ID复制准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:05:29