英文:
How do I Solve Express Validator Middleware Error?
问题
以下是您要翻译的内容:
首先,我有一个像这样的userController:
文件userController.js
const { validationResults } = require('express-validator');
const { userSignUpValidation } = require('../validator/userSignUpValidate');
function userCreation(req, res) {
try{
const errors = validationResults(req);
if(errors) {
return res.status(400)
.json({
error: {
message: errors.array()[0].msg
}
})
}
bcrypt.hash(req.body.userPassword, saltRounds, function(err, hash) {
User.create({
userId: req.body.userId,
userEmail: req.body.userEmail,
userPhoneNumber: req.body.userPhoneNumber,
userPassword: hash
})
.then((user) => {
return res.status(200).json(user);
})
.catch((error) => {
return res.status(400).json.error;
});
});
} catch(error) {
return res.status(400)
.json({
error: {
message: error
}
})
}
}
在validator/userSignUpValidate.js中的代码如下:
'use strict';
const { check } = require('express-validator');
module.exports = [
check('userId').isLength({ min: 5 }).withMessage('用户名至少要有5个字符!'),
check('userPassword').isLength({ min: 6 }).withMessage('密码至少要有6个字符!'),
check('userPhoneNumber').isLength({ min: 10 }).withMessage('电话号码至少要有10个字符!'),
check('userEmail').isEmail().withMessage('您的电子邮件正确吗?请检查并确保正确!')
]
当我在Postman上测试它时,JSON响应总是在userController.js中的catch
块中显示错误,但没有错误消息。
{
"error": {
"message": {}
}
}
我的问题是,为了确保express-validator在正确的位置运行,我应该将代码放在哪里?
英文:
First, I have userController like this:
File userController.js
const { validationResults } = require('express-validator');
const { userSignUpValidation } = require('../validator/userSignUpValidate');
function userCreation(req, res) {
try{
const errors = validationResults(req);
if(errors) {
return res.status(400)
.json({
error: {
message: errors.array()[0].msg
}
})
}
bcrypt.hash(req.body.userPassword, saltRounds, function(err, hash) {
User.create({
userId: req.body.userId,
userEmail: req.body.userEmail,
userPhoneNumber: req.body.userPhoneNumber,
userPassword: hash
})
.then((user) => {
return res.status(200).json(user);
})
.catch((error) => {
return res.status(400).json.error;
});
});
} catch(error) {
return res.status(400)
.json({
error: {
message: error
}
})
}
}
In the validator/userSignUpValidate.js the code like this:
'use strict'
const { check } = require('express-validator');
module.exports = [
check('userId').isLength({ min: 5 }).withMessage('The username at least more than 5 characters!'),
check('userPassword').isLength({ min: 6 }).withMessage('The password at least more than 6 characters!'),
check('userPhoneNumber').isLength({ min: 10 }).withMessage('The phone number at least more than 10 characters!'),
check('userEmail').isEmail().withMessage('Is your email correct? Please be correct!')
]
When I test it on postman, the json response always show error by catch
on userController.js without error message.
{
"error": {
"message": {}
}
}
<br>
My question. To ensure the express-validator run in the right place, where should I put the code?
答案1
得分: 2
首先,你需要从express-validator
中导入validationResult
,在你的代码中你导入了validationResults
。
其次,你没有使用你的userSignUpValidate
中间件。这个中间件可以在控制器中使用,但最好将其应用在userRoute
中,以保持控制器的清晰度。
所以让我们将userSignUpValidate
中间件应用到userRoutes
中。如果文件路径与你的不匹配,请修复它们。
const express = require("express");
const router = express.Router();
const usersController = require("../controllers/userController");
const userSignUpValidate = require("../validator/userSignUpValidate");
router.post("/register", [userSignUpValidate], usersController.userCreation);
module.exports = router;
然后在控制器中,我们需要从express-validator
中导入validationResult
并使用它:
const { validationResult } = require("express-validator");
function userCreation(req, res) {
try {
const errors = validationResult(req);
if(!errors.isEmpty()) {
console.log(errors);
return res.status(400).json({
error: {
message: errors.array()[0].msg
}
});
}
//其他你的代码
} catch (error) {
return res.status(400).json({
error: {
message: error
}
});
}
}
exports.userCreation = userCreation;
当我们发送一个包含3个字符密码的请求体时,就像这样:
{
"userId": "userid",
"userPassword": "123",
"userPhoneNumber": "1234567890",
"userEmail": "abc@gmail.com"
}
响应将会是这样,带有400 - 错误请求:
{
"error": {
"message": "密码至少需要6个字符以上!"
}
}
英文:
Firstly you need to import validationResult
from express-validator
, in your code you are importing validationResults
.
Secondly, you are not using your userSignUpValidate
middleware. This middleware can be used in controller but it is better to appy it in the userRoute to keep controller clean.
So let's apply userSignUpValidate
middleware to the userRoutes.
If the file paths don't match yours, please fix them.
const express = require("express");
const router = express.Router();
const usersController = require("../controllers/userController");
const userSignUpValidate = require("../validator/userSignUpValidate");
router.post("/register", [userSignUpValidate], usersController.userCreation);
module.exports = router;
Then in the controller, we need to import validationResult
from express-validator
and use it:
const { validationResult } = require("express-validator");
function userCreation(req, res) {
try {
const errors = validationResult(req);
if(!errors.isEmpty()) {
console.log(errors);
return res.status(400).json({
error: {
message: errors.array()[0].msg
}
});
}
//other code you have
} catch (error) {
return res.status(400).json({
error: {
message: error
}
});
}
}
exports.userCreation = userCreation;
When we send a request body with a 3 character password like this:
{
"userId": "userid",
"userPassword": "123",
"userPhoneNumber": "1234567890",
"userEmail": "abc@gmail.com"
}
The response will be like this with a 400 - Bad Request:
{
"error": {
"message": "The password at least more than 6 characters!"
}
}
答案2
得分: 0
你应该像这样传递:
const errors = validationResults(req.body);
英文:
you should pass like this
const errors = validationResults(req.body);
答案3
得分: 0
以下是您的代码的中文翻译:
const Joi = require('@hapi/joi');
const loginValidation = data => {
const schema = {
username: Joi.string().min(5).required(),
password: Joi.string().min(5).required(),
deviceId: Joi.string().min(2).required()
};
return Joi.validate(data, schema);
};
module.exports.loginValidation = loginValidation;
// 我的路由文件
const { registerValidation, loginValidation } = require('../../validation');
router.post('/login', async (req, res) => {
try {
// 验证要提交的数据
const { error } = loginValidation(req.body);
if (error) return res.status(200).send(
{
status: 0,
message: "验证错误",
details: error.details[0].message
});
} catch (error) {
res.status(400).send({
status: 0,
message: "失败",
error: error
});
}
});
这段代码正常运行且处于生产模式。
英文:
const Joi = require('@hapi/joi');
const loginValidation = data =>{ const schema = {
username: Joi.string().min(5).required(),
password: Joi.string().min(5).required(),
deviceId: Joi.string().min(2).required()
};
return Joi.validate(data, schema); };
module.exports.loginValidation = loginValidation;
> My Routes File
const { registerValidation, loginValidation } = require('../../validation'); router.post('/login', async (req, res)=>{
try {
//validate the data to be submitted
const { error } = loginValidation(req.body);
if (error) return res.status(200).send(
{
status: 0,
message: "Validarion Error",
details: error.details[0].message
});
} catch (error) {
res.status(400).send({
status: 0,
message: "Failed",
error: error
});
}});
this code works fine and is in production mode
答案4
得分: 0
Here's the translated code snippet:
只需尝试如下,
const express = require('express');
const { check, oneOf, validationResult } = require('express-validator');
const app = express();
// 这个函数需要在控制器中导出
const xxx = (req, res, next) => {
try {
validationResult(req).throw();
res.status(200).send('success');
} catch (err) {
console.log('error message came');
res.status(422).json(err);
}
}
app.get('/', oneOf([
check('lang').isIn(['js', 'react', 'angular'])
]), xxx);
app.listen(4000, () => {
console.log("running server 4k")
})
Please note that the code appears to be in JavaScript and uses the Express.js framework with some validation logic.
英文:
Just try like below,
const express = require('express');
const { check, oneOf, validationResult } = require('express-validator');
const app = express();
//this function you need to export in controller
const xxx = (req, res, next) => {
try {
validationResult(req).throw();
res.status(200).send('success');
} catch (err) {
console.log('error messagecame')
res.status(422).json(err);
}
}
app.get('/', oneOf([
check('lang').isIn(['js', 'react', 'angular'])
]), xxx);
app.listen(4000, ()=>{
console.log("running server 4k")
})
UPDATE 2
I hope below one will help full,
const express = require('express');
const { check, oneOf, validationResult } = require('express-validator');
const app = express();
const xxx = [
check('lang').isIn(['js', 'react', 'angular']),
(req, res, next) => {
try {
validationResult(req).throw();
res.status(200).send('success');
} catch (err) {
console.log('error messagecame')
res.status(422).json(err);
}
}
]
app.get('/', xxx);
app.listen(4000, ()=>{
console.log("running server 4k")
})
Error
https://TruthfulWeirdIrc--five-nine.repl.co?lang=jssddf
Success
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论