在服务器端,它返回未定义,但在客户端,记录值没有问题

问题描述 投票:0回答:1

我已经找了好几天了,但找不到问题所在。我正在尝试在创建用户名和密码后更新用户。 后台更新用户

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

前端表单提交

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 
)

我希望它使用数据库中的这些条目更新用户,但它不会在控制台上记录表单数据,它给出了。

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

此时,这是唯一的错误消息。我尝试过从服务器端的本地存储获取该项目,设置为 cookie,以及一些我不确定的其他建议。

javascript reactjs mongodb jsx crud
1个回答
0
投票

Express 默认不解析 json 数据。您可能缺少 json 解析器中间件。

尝试将以下内容添加到您的代码中,最好是在您首先初始化express的地方;

app.use(express.json())
© www.soinside.com 2019 - 2024. All rights reserved.