【问题标题】:How to keep form data if validation fails in node.js?如果 node.js 中的验证失败,如何保留表单数据?
【发布时间】:2019-08-19 22:09:32
【问题描述】:

我正在尝试使用快速验证器验证表单数据。我在单独的文件中有路由和控制器。我想在验证失败后保留表单字段中的数据。我正在使用快速验证器进行验证。 这是我写的一些代码

router.js

const express = require('express');
const router = express.Router();
const adminController = require('../controllers/adminController');
const { check } = require('express-validator');

router.all('/*',(req,res,next) => {
  req.app.locals.layout = 'admin';
  next();
});

router.route('/')
  .get(adminController.index);

router.route('/news-upload')
  .get(adminController.getNews)
  .post([check('title', 'Title cannot be empty').not().isEmpty(),
     check('description', 'Content cannot be empty!').not().isEmpty()],
     adminController.submitNews);

module.exports = router;

controller.js

submitNews: (req, res) => {
    let error = validationResult(req);

    if (!error.isEmpty()) {
        res.render('admin/news', {
            title: req.body.title,
            description: req.body.description,
            error_message: error.errors[0].msg

        });
    }
    else {----
         }

news.handlebars

<div class = "container">
<h1>Create New Post</h1>

<div class="row p-4">
    <div class="col-md-10">
        <form action="/admin/news-upload" method="post">
        <div class="form-group">
            <lebel for="title">Title</lebel>
            <input type="text" class="form-control" name="title" id="title" 
placeholder="Enter The Title">
        </div>
        <div class="form-group">
            <label for="description">Content</label>
            <textarea name="description" id="description" class="form- 
control" placeholder="Enter your content here" rows="10"></textarea>
        </div>
        <button class="btn btn-outline-success btn-lg" type="submit">Create 
Post</button>

        </form>


    </div>
</div>
</div>

我正在使用 connect-flash 来显示消息。在这里你可以看到

title: req.body.title
description: req.body.description 
error_message: error.errors[0].msg

我正在尝试获取表单值并通过 res.render 将其发送回,但这不起作用。我收到了 Flash 消息,这意味着 error_message: error.errors[0].msg 可以正常工作,并且验证可以正常工作,但我正在尝试保留表单字段的值。如果不像上面那样,我怎么能做到这一点?我也使用车把作为我的视图引擎。谢谢。

【问题讨论】:

    标签: node.js express express-validator connect-flash


    【解决方案1】:

    我认为传递表单名称:req.body.name 会自动设置值。我大错特错了。您还必须在车把文件中使用它 {{name}}。谢谢!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多