ReactJS 提交数据到MongoDB时出现500错误和空值

ReactJS 提交数据到MongoDB时出现500错误和空值

问题描述

问题是当我按下提交按钮时,数据被发送到MongoDB,但我也收到了一个500错误。另一个问题是当我尝试输入用户数据时(在HTML中进行),它发送了空值。有人可以帮助我吗?

这是from.tsx文件的内容

'use client'
import React, {ChangeEvent, FormEvent, useState} from "react";
import axios from 'axios';

const Form : React.FC = () => {
    const [rangeValue, setRangeValue] = React.useState<number | string>("50");
    const [name, setName] = useState('');
    const giveRangeValue = (event: React.ChangeEvent<HTMLInputElement>) => {
        const newRangeValue: string = event.target.value;
        setRangeValue(newRangeValue === "0" ? 0 : newRangeValue);
    }

    const handleSubmit = async (e: FormEvent<HTMLFormElement>)=> {
        e.preventDefault()
        console.log("Name:", name);
        console.log("Range Value:", rangeValue);

        const postData = {
            gebruikersNaam: name,
            risicoScore: rangeValue,
        };
        try {
            const response = await axios.post('/api/risk', postData);

            if (response.status === 200) {
                console.log(response.data);
            } else {
                console.error("Error:", response.data);
            }
        } catch (error){
            console.error(error)
        }
    }

    return (
        <main className={"flex flex-row"}>
            <form onSubmit={handleSubmit}>
                <div className={"form-div space-y-4"}>
                    <div className={"alert flex flex-col items-start"}>
                        <label>
                            Naam
                        </label>
                        <input
                            className={'input'}
                            id="email"
                            value={name}
                            type="text"
                            name="gebruikersNaam"
                            onChange={(e) =>
                                setName(e.target.value)}/>
                    </div>
                    <div className="alert flex flex-row">
                        <input
                            id="range"
                            type={"range"}
                            min={0} max={100}
                            value={rangeValue}
                            onChange={giveRangeValue}>
                        </input>
                        <span className={"value"}>{rangeValue}</span>
                    </div>
                    <div className={"form-btns"}>
                        <button className={"btn mr-5"} type={"submit"}>Maak melding</button>
                        <button className={"btn btn-form ml-10"} type={"button"}><a href={"../"}>Terug</a>
                        </button>
                    </div>
                </div>
            </form>
        </main>
    )
}

export default Form

这是应用程序/ API / 风险

import {getCollection} from "@util/mongodb";
import {Riskscore} from "@/types/db/Riskscore";
import {NextApiRequest, NextApiResponse} from "next";


export async function POST(req: NextApiRequest, res: NextApiResponse) {
    if (req.method === 'POST') {
        try {
            const {gebruikersNaam, risicoScore} = req.body;
            const collection = await getCollection<Riskscore>('netherlands', 'risicoscores');

            const result = await collection.insertOne({
                overlast: "E38",
                gebruikersNaam: "Jack",
                risicoScore: 4,
            });

            if (result.insertedId) {
                res.status(200).json({message: 'Name submitted to MongoDB'});
            } else {
                res.status(500).json({error: 'Error inserting data into MongoDB'});
            }
        } catch (error) {
            res.status(500).json({error: 'Error submitting name to MongoDB'});
        }
    } else {
        res.status(405).end();
    }
}

这是Riskscore.d.ts

import {Document} from "mongodb";

export interface Riskscore extends Document {
    overlast: string
    gebruikersNaam: string
    risicoScore: number
}

解决方案

您的问题在于API响应。

NextJS 13与12的响应处理方式不同,因此您需要调整您的代码以适应此变化。

import {getCollection} from "@util/mongodb";
import {Riskscore} from "@/types/db/Riskscore";
import {NextApiRequest, NextApiResponse} from "next";
import { NextResponse } from 'next/server'

export async function POST(req: NextApiRequest, res: NextApiResponse) {

        try {
            const body = await req.json(); //This is how you access the body in 13
            const {gebruikersNaam, risicoScore} = body;
            const collection = await getCollection<Riskscore>('netherlands', 'risicoscores');

            const result = await collection.insertOne({
                overlast: "E38",
                gebruikersNaam: "Jack",
                risicoScore: 4,
            });

            if (result.insertedId) {
                return NextResponse.json({message: 'Name submitted to MongoDB'}, {status: 200}); //You don't need to specify the status for this 
            } else {
                return NextResponse.json({error: 'Error inserting data into MongoDB'}, {status: 500});
            }
        } catch (error) {
            return NextResponse.json({error: 'Error submitting name to MongoDB'}, {status: 500});
        }
}

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程