express 验证器使用 node express 生成的错误

errors generated by express validator with node express

我正在使用 nodejs、express 和 express-validator。我正在尝试在我的 sign_up 页面上使用快速验证器。 Express-validator 在对象数组中生成错误。
错误:
结果 {
格式化程序:[功能:格式化程序],
错误:[
{
值:未定义,
味精:'Please Enter a Valid Username',
参数:'username'、
位置:'body'
},
{
值:未定义,
味精:'Please enter a valid email'、
参数:'email'、
位置:'body'
},
{
值:未定义,
味精:'Please enter a valid password',
参数:'password'、
位置:'body'
}
]
}

我用postman测试注册操作 并在请求中发送以下内容:
{ “用户名”:“卢巴”, “电子邮件”:“测试@gmail.com”, “密码”:“1234544545@”

}

我的user.js代码:

// Filename : user.js

const express = require("express");
const { check, validationResult} = require("express-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const router = express.Router();

const User = require("../model/User");

/**
 * @method - POST
 * @param - /signup
 * @description - User SignUp
 */

router.post(
    "/signup",
    [
        check("username", "Please Enter a Valid Username")
        .not()
        .isEmpty(),
        check("email", "Please enter a valid email").isEmail(),
        check("password", "Please enter a valid password").isLength({
            min: 6
        })
    ],
    async (req, res) => {
   
        const errors = validationResult(req);
        console.log(errors);
        if (!errors.isEmpty()) {
            console.log("error sign");

            return res.status(400).json({
                errors: errors.array()
            });
            console.log("error sign2");

        }
        console.log("error sign3");

        const {
            username,
            email,
            password
        } = req.body;
        try {
            let user = await User.findOne({
                email
            });
            if (user) {
                return res.status(400).json({
                    msg: "User Already Exists"
                });
            }

            user = new User({
                username,
                email,
                password
            });

            const salt = await bcrypt.genSalt(10);
            user.password = await bcrypt.hash(password, salt);

            await user.save();

            const payload = {
                user: {
                    id: user.id
                }
            };

            jwt.sign(
                payload,
                "randomString", {
                    expiresIn: 10000
                },
                (err, token) => {
                    if (err) throw err;
                    res.status(200).json({
                        token
                    });
                }
            );
        } catch (err) {
            console.log(err.message);
            res.status(500).send("Error in Saving");
        }
    }
);


module.exports = router;

我的索引代码:

const express = require("express");
const bodyParser = require("body-parser");
const user = require("./routes/user"); //new addition
const InitiateMongoServer = require("./config/db");

// Initiate Mongo Server
InitiateMongoServer();

const app = express();

// PORT
const PORT = process.env.PORT || 4000;

// Middleware
//app.use(bodyParser.json());
app.use(express.json());

app.get("/", (req, res) => {
  res.json({ message: "API Working" });
});


app.use("/user", user);

app.listen(PORT, (req, res) => {
  console.log(`Server Started at PORT ${PORT}`);
});

所以请帮助我。有什么问题吗??

编辑:已解决。问题出在邮递员设置中(内容类型必须是JSON)

你启用了吗

app.use(express.json());

因为我看不出你的代码有任何问题(关于 express-validator)。

我建议您在此修复后将检查更改为正文,因为您只想检查正文的内容。

我正在使用中间件来帮助我保持代码简短易读,我将与您分享

function validation(validations: Array<ValidationChain>) {
    return async (req: Request, _res: Response, next: NextFunction) => {
        await Promise.all(validations.map((v) => v.run(req)));
        const errors = validationResult(req);
        if (errors.isEmpty()) {
            return next();
        }
        const msg = errors
            .array()
            .map((er) => `${er.param}`)
            .join(', ');
        const issue = new Issue(400, `missing or invalid params: ${msg}`);
        next(issue);
    };
}

用法:

router.post(
    '/login',
    validation([body('email').isEmail(), body('password').isLength({ min: 5, max: 30 })]),
    async (req: Request, res: Response, next: NextFunction): Promise<void> => {
        ...
    });
``'