Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何解决错误路由。post()需要回调函数,但得到了一个[object Undefined]_Node.js_Express - Fatal编程技术网

Node.js 如何解决错误路由。post()需要回调函数,但得到了一个[object Undefined]

Node.js 如何解决错误路由。post()需要回调函数,但得到了一个[object Undefined],node.js,express,Node.js,Express,我正在使用Express构建一个节点API,但使用JSON文件作为持久数据。 在构建我的路线的过程中,我遇到了以下错误: Route.post()需要回调函数,但得到了一个[object Undefined] 我想要的是创建一个新产品,并通过我的中间件进行验证,如下所示: // Express const express = require("express"); // Router const router = express.Router(); // Product model const

我正在使用Express构建一个节点API,但使用JSON文件作为持久数据。 在构建我的路线的过程中,我遇到了以下错误:
Route.post()需要回调函数,但得到了一个[object Undefined]
我想要的是创建一个新产品,并通过我的中间件进行验证,如下所示:

// Express
const express = require("express");
// Router
const router = express.Router();
// Product model
const product = require("../../models/product");
// Validations middleware
const {
    validateRules
} = require("../../middlewares/validatorRules.middleware");
const {
    productValidationRulesPOST
} = require("../../middlewares/validators.middleware");

// Add a new product
// Validate the rules before start
router.post("/", productValidationRulesPOST, validateRules, (req, res) => {
    // product
    product
        // Using the model to create a Product
        .createProduct(req.body)
        .then( data =>
            // OK product is created
            res.status(201).json({
                message: `The product #${data.id} has been created`,
                content: data
            })
        )
        // Error product not created
        .catch(err => res.status(500).json({ message: err.message }));
});

// Routes
module.exports = router;
我相信我的中间件
productValidationRulesPOST

// Adding body module of express validator
const { body } = require("express-validator");

// Product fields validations
const productValidationRulesPOST = () => {
    return [
        // Name must be min 3 characters and required
        body("name", "Name is required and 3 characters at least")
            .exists()
            .isLength({ min: 3 }),
        // Description must be min 10 characters and required
        body("description", "Description is required and 10 characters at least")
            .exists()
            .isLength({ min: 10 }),
        // Brand required and min length 3
        body("brand", "3 characters at least")
            .exists()
            .isLength({ min: 3 }),
        // Image URL not required
        body("imageUrl").optional(),
        // Price as a number and required
        body("price", "Price is required")
            .exists()
            .isNumeric(),
        // Category not required min length 3
        body("category", "3 characters at least")
            .optional()
            .isLength({ min: 3 })
    ];
};

// Exports the required methods
module.exports = {
    productValidationRulesPOST
}
或者在这一条上:

const { matchedData, validationResult } = require("express-validator");

const validateRules = (req, res, next) => {
    const errors = validationResult(req);

    if (errors.isEmpty()) {
        req.matchedData = matchedData(req);
        return next();
    }

    const extractedErrors = [];
    errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }));

    return res.status(422).json({
        errors: extractedErrors
    });
};

module.exports = validateRules;

问题是,我无法继续前进,因为我无法找到导致错误的线索,也无法真正理解问题是否出在1st或2sd中间件上。

问题在于您的
验证程序
,因为使用
快速验证程序
,您可以将
productValidationRulesPOST
作为中间件传递,但验证是在
回调中完成的

  router.post("/", productValidationRulesPOST, (req, res) => {

      validateRules(req,res)

});
更新

const validateRules = (req, res) => {
    const errors = validationResult(req);

    if (errors.isEmpty()) {
        req.matchedData = matchedData(req);
        // Return true or something that makes sense
    }

    const extractedErrors = [];
    errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }));

    return res.status(422).json({
        errors: extractedErrors
    });
};
我不确定这是否有效,但删除
next()
是有意义的,因为您没有将此函数用作中间件,所以它只是一个普通的javascript
导出函数
尝试更改

router.post("/", productValidationRulesPOST, validateRules, (req, res) => {
 ...
})

用于:


但是我需要做同样的事情,或者我必须像
.product
?问题是,与邮递员的测试给出的是,修改后现在没有响应,这就是为什么我要问还有什么应该更改以使其工作的原因。实际上,我从服务器上没有得到响应,这对我来说是不可行的,因为作为验证者,我给出了一个错误,因为它不是函数
router.post("/", productValidationRulesPOST(), validateRules, (req, res) => {
 ...
})