我的验证有问题,下面是我的代码:
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
阵列中的所有错误,有人能告诉我这里出了什么问题吗?为什么我的req
是undefined
吗?
谢谢你的帮助!
您缺少一个中间件来反序列化请求体。假设您使用JSON作为数据格式,请将其添加到您的server.js:中
app.use(express.json());