我试图使用react表单将数据发送到我的数据库,但它并没有正常工作.当我点击按钮时,函数handleSubmit被调用,但由于某种原因它得到了一个错误.

这是我单击按钮时在控制台中看到的错误:

enter image description here

以下是react表单的代码:

import { useState } from "react";

const ProjectAdminForm = () => {
    const [sdg_desc, setSDGDesc] = useState('')
    const [sdg_num, setSDGNum] = useState('')
    const [goal, setGoal] = useState('')
    const [orginization, setOrginization] = useState('')
    const [source, setSource] = useState('')
    const [location, setLocation] = useState('')
    const [published, setPublished] = useState('')
    const [website_url, setWebsiteURL] = useState('')
    const [assignment_type, setAssignmentType] = useState('')
    const [sharepoint_link, setSharepointLink] = useState('')
    const [statement, setStatement] = useState('')
    const [error, setError] = useState(null)

    const handleSubmit = async (e) => {
        e.preventDefault() // Prevents refresh of page from happening

        console.log('button clicked')
        const project = {sdg_desc, sdg_num, goal, orginization, source, location, published, website_url, assignment_type, sharepoint_link, statement}
                        
        // Sending form response to backend
        const response = await fetch('/api/projects', {
            method: 'POST',
            body: JSON.stringify(project),
            headers: {
                'Content-Type': 'application/json'
            }
        })
        const json = await response.json
        

        // Checking for error
        if (!response.ok) {
            setError(json.error)
        }
        if (response.ok) {
            // Reset form inputs back to empty string
            setSDGDesc('')
            setSDGNum('')
            setGoal('')
            setOrginization('')
            setSource('')
            setLocation('')
            setPublished('')
            setWebsiteURL('')
            setAssignmentType('')
            setSharepointLink('')
            setStatement('')
            
            setError(null)
            console.log('new project added', json)
        }
    }

    return (
        <form className="create" onSubmit={handleSubmit}>
            <h3>Add a New Project</h3>

            <label>SDG Name:</label>
            <input 
                type="text"
                onChange={(e) => setSDGDesc(e.target.value)}
                value={sdg_desc}
            />

            <label>SDG Num:</label>
            <input 
                type="text"
                onChange={(e) => setSDGNum(e.target.value)}
                value={sdg_num}
            />

            <label>Goal:</label>
            <input 
                type="text"
                onChange={(e) => setGoal(e.target.value)}
                value={goal}
            />

            <label>Orginization:</label>
            <input 
                type="text"
                onChange={(e) => setOrginization(e.target.value)}
                value={orginization}
            />

            <label>Source:</label>
            <input 
                type="text"
                onChange={(e) => setSource(e.target.value)}
                value={source}
            />

            <label>Location:</label>
            <input 
                type="text"
                onChange={(e) => setLocation(e.target.value)}
                value={location}
            />

            <label>Published:</label>
            <input 
                type="text"
                onChange={(e) => setPublished(e.target.value)}
                value={published}
            />

            <label>Website URL:</label>
            <input 
                type="text"
                onChange={(e) => setWebsiteURL(e.target.value)}
                value={website_url}
            />

            <label>Assignment Type:</label>
            <input 
                type="text"
                onChange={(e) => setAssignmentType(e.target.value)}
                value={assignment_type}
            />

            <label>Sharepoint Link:</label>
            <input 
                type="text"
                onChange={(e) => setSharepointLink(e.target.value)}
                value={sharepoint_link}
            />

            <label>Statement:</label>
            <input 
                type="text"
                onChange={(e) => setStatement(e.target.value)}
                value={statement}
            />

            <button>Add Project</button>
            {error && <div className="error">{error}</div>}
        </form>
    )
}

export default ProjectAdminForm

下面是它指向的后端api的代码:

// create new project
const createProject = async (req, res) => {
    // adding in a new project
    const {sdg_desc, sdg_num, goal, orginization, source, location, published, website_url, assignment_type, sharepoint_link, statement} = req.body
    try {
        const project  = await Project.create({sdg_desc, sdg_num, goal, orginization, source, location, published, website_url, assignment_type, sharepoint_link, statement})
        res.status(200).json(project)
    } catch (error) {
        res.status(400).json({error: error.message})
    }
}

有人能告诉我为什么当我点击"添加项目"按钮时会出现这个错误吗?

推荐答案

存在多个问题.

const createProject = async (req, res) => {

 const {sdg_desc, sdg_num, goal, orginization, source, location, published, website_url, assignment_type, sharepoint_link, statement} = req.body

const newProject = new Project{(
     sdg_desc: sdg_desc,
     sdg_num : sdg_num,
     goal : goal,
     orginization : orginization,
     source : source,
     location : location,
     published : published,
     website_url : website_url,
     assignment_type : assignment_type,
     sharepoint_link : sharepoint_link,
     statement : statement
)};
    try {
        await newProject.save();
    } catch (error) {
        res.status(500).json({error: error.message})
    }

    res.status(201).json({project: newProject});
}

在前端,当您使用fetch API时,您需要指定到后端的完整链接,因此应该如下所示

const response = await fetch('http://localhost:8000/api/projects', {
            method: 'POST',
            body: JSON.stringify(project),
            headers: {
                'Content-Type': 'application/json'
            }
        })

还要确保发送到后端的数据在前端具有相同的名称

Node.js相关问答推荐

链接Inbox类方法,范围在哪里以及为什么发生变化?

如何从puppeteer的page. evaluate()中获取流数据?(node.js)

NX无法使用缓存运行根级脚本

Sveltekit停靠的应用程序找不到从Build导入的包

NPM:一般的npm二进制依赖可以静态构建吗?

Puppeteer 在本地运行良好,但在 Heroku 中运行不佳

尽管 tsconfig 中提供了正确的路径,但仍出现找不到模块错误

合并Shift对象数组以创建最终的排班表

Node.js中使用ffmpeg如何获取视频截图的位置?

dayjs的isSameOrAfter方法未按预期工作

Indexeddb 获取所有不同于特定值的记录

Fly.io 启动问题:无法从源获取图像或构建错误:构建错误:连接期间出错:发布...

级联定时器和Jest 的异步功能

如何在 node.js 环境中从 WebAssembly (Rust) 调用异步 JavaScript 导入函数?

在 Express-js 中使用路由

使用 nvm-windows 时更新 npm

Node.js, require.main === 模块

使用 Mongoose 进行多对多映射

如何创建安全(TLS/SSL)Websocket 服务器

Firestore:多个条件 where 子句