On the server side, it returns undefined but on the client side, logs the values no problem

42 views Asked by At

I've been searching for days now but cannot find what's wrong. I'm trying to update a user after creating a username and password. Backend updating user

app.put('/users/:userId', async (req, res) => {
    const client = new MongoClient(uri)
    const formData = req.body;

    try {
        await client.connect();
        const database = client.db('app-data')
        const users = database.collection('users');
        console.log("Form data", formData);
        const query = {user_id: formData.userId}
        const updateDocument = {
            $set: {
                first_name: formData?.first_name,
                last_name: formData?.last_name,
                birthdate: formData?.birthdate,
                birth_month: formData?.birth_month,
                birth_year: formData?.birth_year,
                gender: formData?.gender,
                major: formData?.major,
                cleanliness: formData?.cleanliness,
                bio: formData?.bio
            },
        }
        const insertedUser = await users.updateOne(query, updateDocument);
        return res.json(insertedUser);

Frontend form submission

import { useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import React from "react";

const Survey = () => {
    const [formData, setFormData] = useState({
        first_name: '',
        last_name: '',
        birthdate: '',
        birth_month: '',
        birth_year: '',
        gender: '',
        class_rank: '',
        major: '',
        cleanliness: '',
        major_interest: '',
        bio: ''
    })

const navigate = useNavigate();

const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            console.log("Form data: ", formData);
            const userId = localStorage.getItem('userId');
            const response = await axios.put(`http://localhost:8000/users/${userId}`, formData);
     
            navigate('/feed');

            return response;
            
        } catch(err) {
            console.log(err);
        }
    }

    const handleChange = (e) => {
        const value = e.target.value
        const name = e.target.name
        console.log("Updating:", {[name]: value})

        setFormData((prevState) => ({
            ...prevState,
            [name]: value
        }))
    }
    return (
       // HTML form for above values 
)

I'm wanting it update user with these entries in the database but it does not on console logging the form data, it gives.

Form data undefined
{
  acknowledged: true,
  modifiedCount: 0,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 0
}

At this point, that is the only error message. I've tried getting the item from local storage on the server side, setting as cookies, and some other suggestions I'm unsure of.

1

There are 1 answers

1
Jake Haller-Roby On

Express does not parse json data by default. You likely are missing the json parser middleware.

Try adding the following to your code, ideally where you first initialize express;

app.use(express.json())