问题
Hey guys I want to make an messaging system for my upload webpage.
I use express-validator and connect-flash, express-messages
app.js
const { check, validationResult } = require('express-validator');
.
.
.
app.post('/metin/ekle', [
  // username must be an email
  check('baslik', 'Baslik Gereklidir').notEmpty(),
  // password must be at least 5 chars long
  check('konu','Konu gereklidir').notEmpty(),
],function(req, res){
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    req.flash('danger', { errors: errors.array() });//I dont know what do do exactly here
  }
    var metin = new Metin({
      baslik: req.body.baslik,
      yazar: req.body.yazar,
      konu: req.body.konu,
    });
        metin.save(function(err){
          if(err){
            console.log(err);
            return;
          } else {
            req.flash('success', 'Metin Eklendi');
            res.redirect("/metin/"+ metin._id);
          }
        });
      });
And this is my article.pug:
!= messages('my_message_template', locals)
    if errors
        each error, i in errors
          div(class="alert alert-danger") #{error.msg}
ReferenceError: msg is not defined
I dont know what to do exaclty where I decleared validationResult errs. I wrote msg but I know it is wrong. What can I or change my codes in order to message danger when I get express-validation errors?
回答1:
You need change that below line
req.flash({msg});//I dont know what do do exactly here
To
return res.status(422).json({ errors: errors.array() });
then in the view you can find something like that:
{
"errors": [{
    "location": "body",
    "msg": "Invalid value",
    "param": "username"
}]
}
You can see the express-validator docs here
Thanks
来源:https://stackoverflow.com/questions/61922186/express-validator-cannot-show-error-mesages