首页 > 解决方案 > express-validator 显示未定义的已定义值

问题描述

我正在使用 fetch 向服务器发送数据:

const post = async(data)=>{
console.log(data)
const response = await fetch("/comments", {  
method: "POST",
body:JSON.stringify(data)
});
return response.json();
};

数据是控制台记录的,它是一个带有键和值的标准对象。它到达服务器,相同的键和值。

在服务器上,我运行此快速验证以进行清理:

router.use(express.json());
router.post("/",
      body("email").isEmail().normalizeEmail(),
      body("name").trim().escape(),
      body("msg").not().isEmpty().trim().escape(),
      (req,res,next)=>{
      const errors = validationResult(req);
      console.log(errors);
      if (!errors.isEmpty())  { res.status(422).json({ errors: errors.array() }); return};
      try{
      saveComment(req.body, (err,doc) => {
          err?  next(createError(500, "Couldn't save the document. Try again.")):
          res.json({msg:"saved"});
          });
      } catch(e) {
      next(createError(500, ISE));
      }
      });

我得到的是:

Result {
  formatter: [Function: formatter],
  errors: [
    {
      value: undefined,
      msg: 'Invalid value',
      param: 'email',
      location: 'body'
    },
    {
      value: undefined,
      msg: 'Invalid value',
      param: 'msg',
      location: 'body'
    }
  ]
}
POST /comments 422 17.821 ms - 126

错误是什么?

标签: formsexpressvalidation

解决方案


在 fetch 函数中设置标题:

headers: {"Content-Type":"application/json"}

推荐阅读