我目前正在使用 nodejs,我設定了passportjs,我正在嘗試為注冊表設定一些驗證。
這是我目前所擁有的,
路線
// Register :post
router.post('/dashboard/register',
body('firstname').notEmpty().withMessage('First name is required'),
body('lastname').notEmpty().withMessage('Last name is required'),
body('username').notEmpty().withMessage('Username is required'),
body('email').notEmpty().withMessage('An account email is required'),
body('email').isEmail().withMessage('This account email is not valid'),
body('password').notEmpty().withMessage('An account password is required'),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.render('dashboard/register', {
errors: errors
});
} else {
var newUser = new User({
firstname: req.body.firstname,
lastname: req.body.lastname,
username: req.body.username,
email: req.body.email,
password: req.body.password
});
User.createUser(newUser, function(err, user) {
if(err) throw err;
console.log(user);
});
};
});
看法
{{#if errors}}
<div class="alert alert-danger">
{{#each errors}}
<li>{{msg}}</li>
{{/each}}
</div>
{{/if}}
當我觸發錯誤時,我得到了這個

但是,如果我嘗試
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
} else {
...
};
我得到以下
{"errors":[{"value":"","msg":"First name is required","param":"firstname","location":"body"},{"value":"","msg":"Last name is required","param":"lastname","location":"body"},{"value":"","msg":"Username is required","param":"username","location":"body"},{"value":"","msg":"An account email is required","param":"email","location":"body"},{"value":"","msg":"This account email is not valid","param":"email","location":"body"},{"value":"","msg":"An account password is required","param":"password","location":"body"}]}
我不確定我哪里出錯了,我匯入了 express-validator,所以對我來說它似乎沒有捕獲錯誤。
uj5u.com熱心網友回復:
您沒有將陣列傳遞給渲染函式,.array()就像列印 JSON 時那樣使用:
const errors = validationResult(req); // this is returning Result object, not array
if (!errors.isEmpty()) {
res.render('dashboard/register', {
errors: errors.array() // convert Result to array so it can be rendered
});
}
如果不使用.array()該Result物件被傳遞到您的模板,它不能被渲染。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322873.html
標籤:javascript 节点.js 表达 验证
