验证器中未定义快速返回



我的验证有问题,下面是我的代码:

routes.js

var express = require('express');
var router = express.Router();
var hello_controller = require('../api/controllers/helloController');
var { validationRules, validator } = require("../validate/validator");
router.post('/hello/add', validationRules, validator, hello_controller.addHello );
module.exports = router;

控制器.js

exports.addHello = function(req, res) {
res.send("Hello World");
}

验证器.js

module.exports.validationRules= [
body("title")
.exists()
.withMessage("Title is Required")
.isString()
.withMessage("Title must be a String")
.trim(),
//other rules
]
module.exports.validator = validator;

function validator(req, res, next) {
console.log(req.body) //undefined CAN SOMEONE TELL ME WHY?
const errors = validationResult(req);
if (errors.isEmpty()) {
next();
}
const extractedErrors = []
errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }))
return res.json({
errors: extractedErrors
})
}

server.js

const express = require("express");
const app = express();
const helloRoutes = require("./routes/routes");
app.use('/api', helloRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`APP running on port ${PORT}`)
})

在启动POST请求时,我的req返回undefined,而不是通过Postman发送对象,因此,我的validator返回了validationRules阵列中的所有错误,有人能告诉我这里出了什么问题吗?为什么我的requndefined吗?

谢谢你的帮助!

您缺少一个中间件来反序列化请求体。假设您使用JSON作为数据格式,请将其添加到您的server.js:中

app.use(express.json()); 

相关内容

  • 没有找到相关文章