You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Formik提交评论时PostId与UserId后端接收为undefined问题排查

Formik提交评论时后端接收数据为undefined的问题

我用Formik做了个新增评论组件,后端要求评论必须包含PostId、UserId和text字段。提交时前端console.log能输出所有数据,但后端返回400错误,提示“Comment.UserId和Comment.PostId不能为空”,而且后端接收的所有数据都是undefined。后端用Postman测试正常,项目里其他Formik组件也能正常工作,搞不懂为啥这个场景传值失败。

前端CommentForm代码

function newComment(values) {
  const formData = new FormData();
  formData.append("firstName", firstName);
  formData.append("lastName", lastName);
  formData.append("UserId", UserId);
  formData.append("PostId", PostId);
  formData.append("text", values.text);

  console.log("UserId", UserId);
  console.log("firstName", firstName);
  console.log("lastName", lastName);
  console.log("PostId", PostId);
  console.log("text", values.text);
  console.log(props.id);
  axios({
    method: "post",
    url: `http://localhost:8000/api/comments/${props.id}`,
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
      Authorization: `Bearer ${AuthState.token}`,
    },
  })
    .then((res) => {
      if (res.status === 201) {
        console.log("Success");
        window.location.reload(true);
      }
    })
    .catch(function (error) {
     console.log(error)
    });
}


<Formik
              initialValues={{ text: "" }}
              onSubmit={(values) => {
                if (!values.text) {
                  setErrorMessage("Need text");
                } else {
                  newComment(values);
                }
              }}
            >
              <Form>
                <div>
                  <Field
                    name="text"
                    type="contentarea"
                    placeholder="Text Comment"
                  />
                  <ErrorMessage name="text" className="errorInput" />
                </div>
                <Button
                  type="submit"
                  title="Post comment"
                  aria-label="Comment"
                >
                  Comment
                </Button>
              </Form>
            </Formik>

后端Comment控制器代码

exports.createComment = async (req, res, next) => {
  const postObject = req.body;
  const UserId = req.body.UserId;
  const PostId = req.body.PostId;
  const firstName = req.body.firstName;
  const lastName = req.body.lastName;

  if (!req.body) return res.status(403).send("Veillez saisir un texte");

  console.log(req.body);
  console.log(UserId);
  console.log(PostId);
  console.log(firstName);
  console.log(lastName);

  const comment = new Comment({
    text: req.body.text,
    UserId: UserId,
    PostId: PostId,
    firstName: firstName,
    lastName: lastName,
  });
  comment
    .save()
    .then(() => res.status(201).json({ message: "Commentaire posté" }))
    .catch((error) => res.status(400).json({ error }));
};

问题原因与解决方法

核心原因

你用multipart/form-data格式提交数据,但后端没有配置对应的解析中间件,导致无法正确解析FormData,所以req.body为空。另外当前场景没有文件上传需求,用FormData属于没必要的复杂化。

解决方法1:改用JSON格式提交(推荐)

直接提交JSON对象,后端无需额外配置就能解析:
修改前端newComment函数:

function newComment(values) {
  const commentData = {
    firstName: firstName,
    lastName: lastName,
    UserId: UserId,
    PostId: PostId,
    text: values.text
  };

  console.log("UserId", UserId);
  console.log("firstName", firstName);
  console.log("lastName", lastName);
  console.log("PostId", PostId);
  console.log("text", values.text);
  console.log(props.id);
  axios({
    method: "post",
    url: `http://localhost:8000/api/comments/${props.id}`,
    data: commentData,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${AuthState.token}`,
    },
  })
  .then((res) => {
    if (res.status === 201) {
      console.log("Success");
      window.location.reload(true);
    }
  })
  .catch(function (error) {
    console.log(error)
  });
}

解决方法2:保留FormData,后端配置解析中间件

如果一定要用FormData,需要安装multer中间件来解析:

  1. 安装依赖:
npm install multer
  1. 在路由文件中配置:
const multer = require('multer');
const upload = multer();

// 给评论创建接口添加解析中间件
router.post('/comments/:id', upload.none(), commentController.createComment);

另外可以检查下前端PostId是否和URL中的props.id一致,避免传错值。


内容的提问来源于stack exchange,提问作者Fenrir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 05:25:40