Getting 500 Error and Null Values When Submitting Data to MongoDB

The problem is that when I press the submit button, it sends the data to MongoDB, but I also receive a 500 error. Another issue is that when I try to input user data (inside the html), it sends null. Can someone help me?

This is the 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

This is the app/api/risk

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();
    }
}

this is the Riskscore.d.ts

import {Document} from "mongodb";

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

NextJS 13 handles the responses differently from 12 so you will need to adjust your code to this.
Now it work

import {getCollection} from "@util/mongodb";
import {Riskscore} from "@/types/db/Riskscore";

export async function POST(request: Request) {
    try {
        const body = await request.json(); //This is how you access the body in 13
        const {gebruikersNaam, risicoScore} = body;
        console.log("Received Data: gebruikersNaam =", gebruikersNaam, "risicoScore =", risicoScore);
        const collection = await getCollection<Riskscore>('netherlands', 'risicoscores');

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

        if (result.insertedId) {
            body.status(200).json({message: 'Name submitted to MongoDB'});
        } else {
            body.status(500).json({error: 'Error inserting data into MongoDB'});
        }
    } catch (error) {
        console.log(error)
    }
}
1 Like