【问题标题】:sails.js 0.10.0-rc4 cannot flash message to ejs viewsails.js 0.10.0-rc4 无法将消息闪烁到 ejs 视图
【发布时间】:2014-03-07 07:28:00
【问题描述】:

在服务器js中

 if (!user) {
      if (isEmail) {
        req.flash('error', 'Error.Passport.Email.NotFound');
        sails.log.warn('User Email not fond.');
      } else {
        req.flash('error', 'Error.Passport.Username.NotFound');
        sails.log.warn('User name not found.');
      }

ejs 视图

<form role="form" action="/auth/local" method="post">
    <input type="text" name="identifier" placeholder="Username or Email">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Sign in</button>
</form>

<% if (typeof message!== 'undefined') { %>
<%= message %>
<% } else { %>
You E-mail and passport is correct!
<% } %>

如果我输入了一封错误的电子邮件或护照,ejs 视图不会显示任何错误消息,为什么? 如何将错误消息闪烁到 ejs 视图?我做错了什么吗? 对不起我的英语不好。 谢谢。

【问题讨论】:

    标签: node.js express sails.js


    【解决方案1】:

    实际上,req 会自动传递到您的视图中,因此您可以在视图中执行以下操作:

    <%- req.flash('message') %>
    

    您无需手动将消息传递到您的视图。

    【讨论】:

    • Scott - 我们如何使用 ejs 在视图中使用条件检查 Flash 消息?似乎只要在 if 语句中使用它,会话闪存就会被破坏。示例:&lt;% if (req.flash('errors').length !== 0) { %&gt;
    • 是的,访问闪存消息将清除它。如果你想先检查它是否存在,你可以使用req.session.flash
    • 啊!很高兴知道。在等待您的专业知识时,我决定将其传递给变量中的视图。有了你刚刚分享的内容,现在我应该可以清理 res.view()... 我喜欢干净!与往常一样,谢谢……你太棒了,因为我开始熟悉sails.js和node.js!
    【解决方案2】:

    Flash 中间件将 Flash 消息存储在会话中。你仍然需要将它传递给你的视图并自己渲染它:

    app.get('/flash', function(req, res){
      // Set a flash message by passing the key, followed by the value, to req.flash().
      req.flash('info', 'Flash is back!')
      res.redirect('/');
    });
    
    app.get('/', function(req, res){
      // Get an array of flash messages by passing the key to req.flash()
      res.render('index', { messages: req.flash('info') });
    });
    

    【讨论】:

    • “你还是得把它传递给你的视图,然后自己渲染”这就是我想要的。我在这里卡了一个月。谢谢
    • 您不必将视图传递给它!但是您确实需要以不同的方式呈现它(请参阅我的回答)。
    【解决方案3】:

    在 Sailsjs v0.10.0-rc8 中使用 req.session.flash 检查消息是否存在会导致 undefined 错误。

    这是我最终使用的解决方案:

      <% var errors = req.flash('error'); %>
        <% if ( Object.keys(errors).length > 0 ) { %>
        <div class="alert alert-danger">
          <button type="button" class="close" aria-hidden="true" data-dismiss="alert">&times;</button>
          <ul>
            <% Object.keys(errors).forEach(function(error) { %>
              <li><%- JSON.stringify(errors[error]) %></li>
            <% }) %>
          </ul>
        </div>
       <% } %>
    

    更新

    我想出了如何在阅读消息之前检查 Flash 消息是否存在:

       <% if (req.session.flash && req.session.flash.error) { %>
          <% var errors = req.flash('error') %>
          <div class="alert alert-danger">
            <button type="button" class="close" aria-hidden="true" data-dismiss="alert">&times;</button>
            <ul>
              <% Object.keys(errors).forEach(function(error) { %>
                <li><%- JSON.stringify(errors[error]) %></li>
              <% }) %>
            </ul>
          </div>
       <% } %>
    

    【讨论】:

      【解决方案4】:

      我发现以下自定义验证方法比使用上述方法更有帮助。我想你最终会在某个时候想要自定义验证消息,对吧?

      https://gist.github.com/basco-johnkevin/8436644

      注意:我创建了一个名为 api/services/ValidationService.js 的文件,并将 gist 代码放在这里。这样我就不必在 Controller 中要求它了。

      在控制器中:

      create: function(req, res, next) {
          //Create a User with the params sent from the signup form
          //
          User.create( req.params.all(), function userCreated( err, user ) {
              // If there's an error
              // 
              if(err) {
                  if(err.ValidationError) {
                      errors = ValidationService.transformValidation(User, err.ValidationError);
                      sails.log.warn(errors);
                      req.flash('error', errors);
                  }
      
                  // If error redirect back to the sign-up page
                  return res.redirect('/user/new');
              }
      
              // After successfully creating the user 
              // redirect the to the show action
              res.json(user);
          });
      }
      

      在我的用户模型中:

      module.exports = {
      
        schema: true,
      
        attributes: {
          name: {
              type: 'string',
              required: true
          },
      
          title: {
              type: 'string'
          },
      
          email: {
              type: 'string',
              email: true,
              required: true,
              unique: true
          },
      
          encryptedPassword: {
              type: 'string',
              minLength: 6,
              required: true
          }
      
        },
      
        validation_messages: {
          name: {
              required: 'You must supply a valid name.'
          },
      
          email: {
              email: 'You must supply a valid email address.',
              required: 'You must supply a valid email address.',
              unique: 'An account with this email address already exists.'
          },
      
          encryptedPassword: {
              minLength: 'Your password must be atleast 6 characters long.',
              required: 'You must supply a password that is atleast 6 characters long.'
          }
        }
      
      };
      

      这就是我最终在用户注册表单视图中看到的内容。嗯……一定有更好的办法。

      <% if (req.session.flash && req.session.flash.error) { %>
        <% var errors = req.flash('error') %>
        <div class="alert alert-danger">
          <button type="button" class="close" aria-hidden="true" data-dismiss="alert">&times;</button>
          <ul>
            <% Object.keys(errors).forEach(function(error) { %>
              <% Object.keys(errors[error]).forEach(function(error_message) { %>
              <% Object.keys(errors[error][error_message][0]).forEach(function(error_message_res) { %>
              <li>
                  <%- errors[error][error_message][0][error_message_res] %>
              </li>
              <% }); %>
              <% }); %>
            <% }); %>
          </ul>
        </div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-05
        • 1970-01-01
        • 1970-01-01
        • 2019-04-18
        • 1970-01-01
        • 2019-03-05
        • 1970-01-01
        相关资源
        最近更新 更多