Express Validator Cannot Show Error Mesages

…衆ロ難τιáo~ 提交于 2020-05-30 08:49:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!