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

Express JS对接Notion API时POST/GET请求报错求助

问题修复方案

核心问题1:提交表单时req.body undefined

原因:Express中间件注册顺序错误,express.json()(用于解析JSON请求体)和cors()放在了路由定义之后,导致路由处理请求时还未启用请求体解析,req.body自然为undefined。
修复:调整中间件顺序,先注册中间件再定义路由:

const express = require('express')
const axios = require('axios')
const cors = require('cors')
const app = express()
const port = 3002

const secretKey = 'secret_[KEY REPLACED]'

const headers = {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${secretKey}`,
    'Notion-Version': '2022-02-22',
}

// 先注册中间件
app.use(cors())
app.use(express.json())

// 再定义路由
app.post('/:database_id', async (req, res) => {
  // ... 后续路由逻辑
})

app.get('/:database_id', async (req, res) => {
  // ... 后续路由逻辑
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

核心问题2:POST路由与前端请求路径不匹配+Notion请求参数错误

原因1:前端POST请求的是动态数据库ID路径,但服务器POST路由是硬编码的固定ID,导致请求无法匹配到正确的处理逻辑。
原因2:Notion请求的parent字段存在笔误(dat704f58825cf841759f76733c5794e8aaabase_id是错误写法)。
修复:把POST路由改成动态参数,修正Notion请求参数:

app.post('/:database_id', async (req, res) => {
  try {
    const { name, email } = req.body
    const { database_id } = req.params // 获取动态传入的数据库ID
    await axios({
      method: 'POST',
      url: 'https://api.notion.com/v1/pages',
      headers,
      data: {
        parent: { database_id }, // 修正笔误
        properties: {
          "Name": { "title": [{ text: { content: name } }] },
          "Email": { "email": email }
        }
      }
    })
    res.status(200).json({ message: '提交成功' }) // 必须返回响应,避免前端挂起
  } catch (err) {
    console.error('Notion API请求失败:', err.response?.data || err.message)
    res.status(500).json({ error: '提交失败,请检查服务器日志' })
  }
})

问题3:启动服务器显示“Cannot GET /”

原因:根路径/没有对应的路由处理逻辑。
修复:添加根路径路由:

app.get('/', (req, res) => {
  res.send('Notion Form API 运行中,请访问带有数据库ID的路径')
})

问题1:页面刷新时出现错误

原因:页面渲染时可能访问了db对象的属性,但db初始值为空对象,首次渲染/刷新时会因属性不存在报错。
修复:

  1. 给db设置合理初始值:
const [db, setDB] = useState({ properties: {}, title: [] });
  1. 渲染时添加可选链或加载状态:
// 示例:显示数据库标题时添加可选链
<Heading>{db.title?.[0]?.plain_text || '加载中...'}</Heading>

// 或者在数据加载完成前显示加载组件
if (!db.title) {
  return <Spinner />;
}

前端优化:添加错误处理

避免表单提交静默失败,给onSubmit添加异常捕获:

const onSubmit = async (e) => {
  e.preventDefault();
  try {
    const response = await fetch(`http://localhost:3002/${database_id}`, {
      method: 'POST',
      body: JSON.stringify({ email, name }),
      headers: { "Content-Type": 'application/json' }
    });
    if (!response.ok) throw new Error('提交失败');
    alert('提交成功!');
    // 重置表单
    setName('');
    setEmail('');
  } catch (err) {
    console.error(err);
    alert('提交失败,请重试');
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:45:39