forms - 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
错误是什么?
解决方案
在 fetch 函数中设置标题:
headers: {"Content-Type":"application/json"}
推荐阅读
- java - 我无法安装 Netbeans10
- css - 带有 CSS 变量的文本阴影
- visual-studio - Visual Studio 2019 中的 Xamarin Live Player
- javascript - 如何从已部署的 Firebase 应用程序的云函数中获取
- java - Android - 将多个 .CSV 文件导入 SQLite 数据库中的多个表
- jobs - Quartz.NET 不执行也不引发作业错误
- c++ - 使用遗留代码(使用 reinterpret_cast)真的是一种好技术吗?
- s4sdk - vdm 生成的类没有 getter
- vue.js - 在没有 vue CLI 的情况下使用 require,只需 vue
- python - 循环遍历多个 CSV 文件