我有這一系列密碼更改的驗證規則,但有一個錯誤說:
“'await' 運算式只允許在異步函式中和模塊的頂層使用。”
const validationRules = [
body('current_password')
.exists()
.not()
.isEmpty()
.withMessage('current password is required')
.custom((value, { req }) => {
const { id } = req.user;
const { current_password } = req.body;
const detailUser = await User.where('id', id).fetch({
withRelated: ['roles'],
});
if (!detailUser) {
throw new Error('User not found');
}
if (
!bcrypt.compareSync(current_password, detailUser.attributes.password)
) {
const errorMessage =
'Current password you entered did not match our records';
Logger.error(errorMessage);
throw new Error(errorMessage);
}
return true;
}),
body('new_password')
.exists()
.not()
.isEmpty()
.withMessage('New password is required'),
body('confirm_password')
.exists()
.not()
.isEmpty()
.custom((value, { req }) => {
if (value !== req.body.new_password) {
throw new Error('Password confirmation does not match password');
}
return true;
}),
];
我應該把異步放在哪里來修復這個錯誤,請幫忙
uj5u.com熱心網友回復:
注意:異步函式必須回傳已解決或拒絕的 Promise,因為真值或假值不會停止鏈(#1028)。
來源:自定義驗證器鏈
因此,您需要拒絕使用錯誤訊息并async在自定義處使用function(){}
對您的代碼進行這些更改,
const validationRules = [
body('current_password')
.exists()
.not()
.isEmpty()
.withMessage('current password is required')
.custom(async (value, { req }) => {
const { id } = req.user;
const { current_password } = req.body;
const detailUser = await User.where('id', id).fetch({
withRelated: ['roles'],
});
if (!detailUser) {
return Promise.reject('User not found');
}
if (
!bcrypt.compareSync(current_password, detailUser.attributes.password)
) {
const errorMessage =
'Current password you entered did not match our records';
Logger.error(errorMessage);
return Promise.reject(errorMessage);
}
return Promise.resolve();
}),
body('new_password')
.exists()
.not()
.isEmpty()
.withMessage('New password is required'),
body('confirm_password')
.exists()
.not()
.isEmpty()
.custom(async (value, { req }) => {
if (value !== req.body.new_password) {
return Promise.reject('Password confirmation does not match password');
}
return Promise.resolve();
}),
];
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/505013.html
標籤:表示
下一篇:為什么NodeJsreq.get('host')結果到數字海洋上的localhost:3000而不是我的實際域名
