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

React表单提交数据库失败,handleSubmit函数触发报错求助

问题原因及解决方案

核心错误原因

你代码里的关键问题出在React表单的handleSubmit函数中:调用response.json时缺少了括号。json()是一个异步方法,必须通过response.json()的方式调用才能将响应体解析为JSON对象。你当前的写法response.json只是引用了这个方法本身,并未执行解析操作,导致后续尝试访问json.error时,json是函数而非预期的JSON对象,直接触发了错误。

修正代码

将handleSubmit里的响应解析部分修改为:

// 修正后的fetch响应解析逻辑
const response = await fetch('/api/projects', {
    method: 'POST',
    body: JSON.stringify(project),
    headers: {
        'Content-Type': 'application/json'
    }
})
const json = await response.json() // 此处添加括号,调用json()方法

额外建议

为了让代码更健壮,还可以补充以下优化:

  • 给fetch逻辑添加try/catch捕获网络异常,避免因后端服务未启动或网络问题导致的未处理错误:
const handleSubmit = async (e) => {
    e.preventDefault()
    const project = {sdg_desc, sdg_num, goal, orginization, source, location, published, website_url, assignment_type, sharepoint_link, statement}
    
    try {
        const response = await fetch('/api/projects', {
            method: 'POST',
            body: JSON.stringify(project),
            headers: {
                'Content-Type': 'application/json'
            }
        })
        const json = await response.json()

        if (!response.ok) {
            setError(json.error)
        }
        if (response.ok) {
            // 重置表单输入
            setSDGDesc('')
            setSDGNum('')
            setGoal('')
            setOrginization('')
            setSource('')
            setLocation('')
            setPublished('')
            setWebsiteURL('')
            setAssignmentType('')
            setSharepointLink('')
            setStatement('')
            
            setError(null)
            console.log('new project added', json)
        }
    } catch (networkError) {
        setError('网络请求失败,请检查后端服务状态')
        console.error('网络错误:', networkError)
    }
}
  • 确认后端/api/projects的POST路由已正确配置,能映射到createProject函数
  • 核对数据库Project模型的字段与前端传递的字段完全一致,避免因字段不匹配导致的创建失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:21:24