【问题标题】:Express return undefined in validator在验证器中快速返回未定义
【发布时间】:2021-05-12 17:04:45
【问题描述】:

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

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;

controller.js

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

validator.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

感谢您的帮助!

【问题讨论】:

    标签: javascript node.js typescript express validation


    【解决方案1】:

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

    app.use(express.json()); 
    

    【讨论】:

    • 谢谢!我会在几分钟内接受您的回答
    • 提前谢谢!
    猜你喜欢
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多