我想我已经非常接近解决这个问题了。我只是在发现错误后尝试重新填充表单数据。在我下面的示例中,年龄和血小板计数都应该重新填充,但它们没有。
模型名称:Store.js
storeController.js
exports.store_create_post = [
body('age', 'Please enter age').isLength({ min:1 }),
body('platelet_count', 'Please enter platelet count').isLength({ min: 1 }),
// sanitizeBody('age').escape(),
(req, res, next) => {
//Extract the validation errors from a request.
const errors = validationResult(req);
//Store form values for post data when error caught
var predModel = new Store(
{
age: req.body.age,
platelet_count: req.body.platelet_count
}
);
if (!errors.isEmpty()) {
//Validation or Sanitation checks did not pass
res.render('predictionModel', {title: 'Risk Calculator', Store: predModel, errors: errors.array()});
return;
}
我认为我的问题是我无法弄清楚 res.render (Store: predModel) 中的参数正在做什么。我可以向后切换参数 (predModel: Store),它仍然可以正常工作。
这是我的路线:
index.js
//Get request for PredctionModel Form
router.get('/predictionModel', storeController.store_create_get);
//Post request for PredictionModel
router.post('/predictionModel', storeController.store_create_post);
如有任何建议,我们将不胜感激。
更新。这是我的表单页面,为了方便查看,删除了大部分内容:
_modelForm.pug
mixin predictionModelForm(store = {})
form(action="/predictionModel" method="POST" class="card")
label(for="age") How old is the patient (years)?
input(type='number', name='age', style='width: 100px;', placeholder="40-89")
input(type="submit" value="Predicted Risks" class="button" style='width: 50%;')
最佳答案
不要在渲染对象中使用构造函数。定义一个简单的对象
var predModel = {
age: req.body.age,
platelet_count: req.body.platelet_count
}
然后像这样渲染
res.render('predictionModel', {title: 'Risk Calculator', predModel: predModel, errors: errors.array()});
在您的输入中,您可以通过这种方式增加值(value)。
input(type='number', name='age', style='width: 100px;', value=predModel.age, placeholder="40-89")
此外,由于您渲染相同的 pug 文件,因此您应该检查您渲染的属性(例如 predModel
)是否未定义。
关于node.js - NodeJS Express : Repopulate form after error found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55346094/