如何在Node.js中的车把栏模板中显示错误消息

时间:2019-03-18 13:52:02

标签: node.js express handlebars.js

我正在尝试以把手模板形式显示红色错误消息。我正在使用express-validator来验证表单的不同输入字段。目前,它只能通过以json形式返回错误消息来工作。如何在视图中向用户显示这些error消息。我是Node的新手。

form.hbs

<!DOCTYPE html>
<html lang="en">
<body>
<h2>Enter Details</h2><br />
<div>
    {{# if errors }}
        {{# each errors }}
            <p class="alert alert-danger">{{ this.msg }}</p>
        {{/each}}
    {{/if}}
    <form role="form" data-toggle="validator" method="post">
        <div class="form-group row">
            <label class="col-sm-2 col-form-label" for="inputSchoolCode">School code</label>
            <div class="col-sm-10">
                <input class="form-control" id="inputSchoolcode" type="text" name="schoolCode" placeholder="School code" required="" />
                <div class="help-block with-errors"></div>
            </div>
        </div>
        <div class="form-group row">
            <div class="col-sm-10"></div>
            <button class="btn btn-primary btn-lg" type="submit">Submit</button>
        </div>
    </form>
</div>
</body>
</html>

app.js

const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const flash = require('connect-flash');
const session = require('express-session');
const hbs = require('hbs');
const app = express();
app.use(flash());

app.use(session({
  cookie: { maxAge: 6000 },
  secret: 'futuresonic',
  resave: false,
  saveUninitialized: false
}));

app.get('/', (req, res) => {
  res.render('form', { title: 'ContactForm', success: req.session.success, errors: req.session.errors});
  req.session.errors = null;
});

app.get('/done', (req, res) => {
  res.render('done');
});

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: true }));

form.js

const express = require('express');
const router = express.Router();
const { validationResult, check } = require('express-validator/check');
const firebaseManager = require('../FirebaseManager/firebaseManager');

let errorMessage = 'Fields cant be empty';
let validators = [
    check('schoolCode')
        .not().isEmpty().withMessage(errorMessage)
        .isUppercase().withMessage(errorMessage)
];

router.post('/', validators, (req, res) => {
      checkForErrorsAndWriteToFirebase(req, res);
});

const checkForErrorsAndWriteToFirebase = (req, res) => {
 const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(422).json({ errors: errors.array() });
    } else {
        firebaseManager(req);
        res.redirect('/done');
       }
    };
  module.exports = router;

0 个答案:

没有答案