Node.js 无法使用FormData从表单中获取数据

Node.js 无法使用FormData从表单中获取数据,node.js,reactjs,next.js,backend,form-data,Node.js,Reactjs,Next.js,Backend,Form Data,我正在为仪表板创建一个“编辑配置文件”页面。我使用的技术有Next.js、Node.js和MongoDB 注意:如果您只是想了解问题,请跳到后端部分 前端 首先,让我解释一下前端部分 我正在使用以引用inputfields中的数据(名称、bio)。它们工作得很好 一切正常问题出在handlesbuit()event\u处理程序中。 我正在使用FormData将表单数据发送到后端API 如果你在想为什么我不使用普通的body对象来发送数据,原因是我必须在以后添加profile picture更

我正在为仪表板创建一个“编辑配置文件”页面。我使用的技术有Next.js、Node.js和MongoDB

注意:如果您只是想了解问题,请跳到后端部分

前端 首先,让我解释一下
前端部分

  • 我正在使用以引用inputfields中的数据(名称、bio)。它们工作得很好
  • 一切正常问题出在
    handlesbuit()
    event\u处理程序中。
    • 我正在使用
      FormData
      将表单数据发送到后端API
    • 如果你在想为什么我不使用普通的body对象来发送数据,原因是我必须在以后添加profile picture更新,我必须发送文件,据我所知,我们不能用一个对象来做这件事,是的,我只是想告诉你,如果我用了那个对象的部分,但不能用它来更新profilepicture的话,它工作得很好
    • 我为引用安慰出来的值都是好的,处理程序的其余部分就如它所写的一样,在这一点上找不到任何奇怪的东西

我在这个问题上遇到了一个难题。 我是解决它的使用2表,一个表单用于获取用户的信息,如电子邮件,密码和其他发送用户的图片。 也许对这种情况有最好的实践


    import { useUser } from '../../../lib/hooks';
import React, { useState, useEffect, useRef } from 'react';
import Head from 'next/head';
import { ImBook, ImListNumbered } from 'react-icons/im';
import { AiFillGithub, AiOutlineTwitter, AiFillFacebook, AiFillInstagram, AiFillLinkedin } from 'react-icons/ai'
import { FaFacebook, FaStackOverflow } from 'react-icons/fa';

const ProfileSection = () => {
    const [user, { mutate }] = useUser();
    const [isUpdating, setIsUpdating] = useState(false);
    const nameRef = useRef();
    const profilePictureRef = useRef();
    const bioRef = useRef();
    const [msg, setMsg] = useState({ message: '', isError: false });

    useEffect(() => {
        nameRef.current.value = user.name;
        bioRef.current.value = user.Bio;
    }, [user]);


    const handleSubmit = async (event) => {
        event.preventDefault();
        if (isUpdating) return;
        setIsUpdating(true);

        console.log(nameRef.current.value); //Testing
        console.log(bioRef.current.value);  //Testing

        const formData = new FormData();
        formData.append('name', nameRef.current.value);
        formData.append('Bio', bioRef.current.value);
        console.log(formData.get('name'));
        const res = await fetch('/api/user', {
            method: 'PATCH',
            body: formData,
        });
        if (res.status === 200) {
            const userData = await res.json();
            mutate({
                user: {
                    ...user,
                    ...userData.user,
                },
            });
            setMsg({ message: 'Profile updated' });
        } else {
            setMsg({ message: await res.text(), isError: true });
        }
    };


    return (
        <>
            <Head>
                <title>Settings</title>
            </Head>
            <main>
                <div class="row">
                    <div class="col s12 m12">
                        <div className="card-panel br-10">
                            {msg.message ? <p style={{ color: msg.isError ? 'red' : '#0070f3', textAlign: 'center' }}>{msg.message}</p> : null}
                            <form onSubmit={handleSubmit}>
                                <div className="row">
                                    <div className="col s12 m6 l6">
                                        <label htmlFor="name">
                                            Name
                                         <input
                                                required
                                                id="name"
                                                name="name"
                                                type="text"
                                                ref={nameRef}
                                            />
                                        </label>
                                    </div>
                                    <div className="col s12 m6 l6">
                                        <label htmlFor="bio">
                                            Bio
                                            <textarea
                                                id="bio"
                                                name="bio"
                                                type="text"
                                                ref={bioRef}
                                            />
                                        </label>
                                    </div>
                                </div>

                                <div className="center-align">
                                    <button disabled={isUpdating} className="btn" type="submit" >Save</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </main>
        </>
    );
};

const SettingPage = () => {
    const [user] = useUser();

    if (!user) {
        return (
            <>
                <p>Please sign in</p>
            </>
        );
    }
    return (
        <>
            <ProfileSection />
        </>
    );
};

export default SettingPage;

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    import { useUser } from '../../../lib/hooks';
    import React, { useState, useEffect, useRef } from 'react';
    import Head from 'next/head';
    import { ImBook, ImListNumbered } from 'react-icons/im';
    import { AiFillGithub, AiOutlineTwitter, AiFillFacebook, AiFillInstagram, AiFillLinkedin } from 'react-icons/ai'
    import { FaFacebook, FaStackOverflow } from 'react-icons/fa';

    const ProfileSection = () => {
        const [user, { mutate }] = useUser();
        const [isUpdating, setIsUpdating] = useState(false);
        const nameRef = useRef();
        const profilePictureRef = useRef();
        const bioRef = useRef();
        const [msg, setMsg] = useState({ message: '', isError: false });

        useEffect(() => {
            nameRef.current.value = user.name;
            bioRef.current.value = user.Bio;
        }, [user]);


        const handleSubmit = async (event) => {
            event.preventDefault();
            if (isUpdating) return;
            setIsUpdating(true);

            console.log(nameRef.current.value);
            console.log(bioRef.current.value);

            const formData = new FormData();
            formData.append('name', nameRef.current.value);
            formData.append('Bio', bioRef.current.value);
            console.log(formData.get('name'));
            const res = await fetch('/api/user', {
                method: 'PATCH',
                body: formData,
            });
            if (res.status === 200) {
                const userData = await res.json();
                mutate({
                    user: {
                        ...user,
                        ...userData.user,
                    },
                });
                setMsg({ message: 'Profile updated' });
            } else {
                setMsg({ message: await res.text(), isError: true });
            }
        };


        return (
            <>
                <Head>
                    <title>Settings</title>
                </Head>
                <main>
                    <div class="row">
                        <div class="col s12 m12">
                            <div className="card-panel br-10">
                                {msg.message ? <p style={{ color: msg.isError ? 'red' : '#0070f3', textAlign: 'center' }}>{msg.message}</p> : null}
                                <form onSubmit={handleSubmit}>
                                    <div className="row">
                                        <div className="col s12 m6 l6">
                                            <label htmlFor="name">
                                                Name
                                             <input
                                                    required
                                                    id="name"
                                                    name="name"
                                                    type="text"
                                                    ref={nameRef}
                                                />
                                            </label>
                                        </div>
                                        <div className="col s12 m6 l6">
                                            <label htmlFor="bio">
                                                Bio
                                                <textarea
                                                    id="bio"
                                                    name="bio"
                                                    type="text"
                                                    ref={bioRef}
                                                />
                                            </label>
                                        </div>
                                    </div>

                                    <div className="center-align">
                                        <button disabled={isUpdating} className="btn" type="submit" >Save</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </main>
            </>
        );
    };

    const SettingPage = () => {
        const [user] = useUser();

        if (!user) {
            return (
                <>
                    <p>Please sign in</p>
                </>
            );
        }
        return (
            <>
                <ProfileSection />
            </>
        );
    };

    export default SettingPage;

    import nextConnect from 'next-connect';
import middleware from '../../../middlewares/middleware';
import { extractUser } from '../../../lib/api-helpers';

const handler = nextConnect();
handler.use(middleware);
handler.get(async (req, res) => res.json({ user: extractUser(req) }));

handler.patch(async (req, res) => {
    if (!req.user) {
        req.status(401).end();
        return;
    }

    const { name, Bio } = req.body;

    await req.db.collection('users').updateOne(
        { _id: req.user._id },
        {
            $set: {
                name:name,
                Bio: Bio,
            },
        },
    );
    res.json({ user: { name, Bio } });
});

export default handler;