【问题标题】:How to handle validation messages returned by Sails JS?如何处理 Sails JS 返回的验证消息?
【发布时间】:2019-11-15 05:48:08
【问题描述】:

希望你做得很好!

我正在开发 SailsJS 网络应用程序并为控制器使用动作结构。

这是我的user/login 操作:

  module.exports = {
    friendlyName: 'Login',

    description: 'Login user.',

    inputs: {
      email: {
        description: 'user email.',
        type: 'string',
        required: true
      },
      password: {
        description: 'user password.',
        type: 'string',
        required: true
      }
    },

    exits: {
      success: {
        statusCode: 200,
        responseType: 'view',
      },       
    },

    fn: async function (inputs, exits) {
      // All done.
      return 'hello world';
    }
  };

这是登录表单的html代码:

    <div class="row">
      <div class="valign-wrapper">
          <div class="col s6 z-depth-4 card-panel">
            <form class="col s12 login-form" method="POST" action="/login">
              <input type="hidden" name="_csrf" value="<%= _csrf %>" />
              <div class="card-content">
                <h5 class="card-title center-align">Login</h5>
                <div class="row margin">
                  <div class="input-field col s12">
                    <input id="email" type="email" class="validate">
                    <label for="email">Email</label>
                    <div class="invalid-feedback" v-if="formErrors.emailAddress">Please provide a valid email address.</div>
                  </div>
                </div>
                <div class="row margin">
                  <div class="input-field col s12 right">
                    <input id="password" type="password" class="validate">
                    <label for="email">Password</label>
                  </div>
                </div>
                <div class="row">
                  <button class="btn waves-effect waves-light right" type="submit" name="action">Login</button>
                </div>            
              </div>
            </form>
          </div>
        </center>
      </div>
    </div>

每当我提交空白表单时,我都会收到以下错误:

    {
      "code": "E_MISSING_OR_INVALID_PARAMS",
      "problems": [
        "\"email\" is required, but it was not defined.",
        "\"password\" is required, but it was not defined."
      ],
      "message": "The server could not fulfill this request (`POST /login`) due to 2 missing or invalid parameters.  **The following additional tip will not be shown in production**:  Tip: Check your client-side code to make sure that the request data it sends matches the expectations of the corresponding parameters in your server-side route/action.  Also check that your client-side code sends data for every required parameter.  Finally, for programmatically-parseable details about each validation error, `.problems`. "
    }

现在,问题是我无法找到以更漂亮的方式处理此错误的方法。

我希望你们中的一个人能引导我走上正确的道路。

谢谢,

【问题讨论】:

  • 我创建了一个钩子来解析此类错误,并通过调用函数sails.hooks.error.humanize(err) 在控制器的响应中添加人类可读的errorMessage。如果你愿意,我可以分享代码。您使用的是哪个版本的风帆(是否支持挂钩)?
  • 我使用的是最新版本,1.0

标签: javascript validation sails.js


【解决方案1】:

U 可以转换 api/responses/badRequest 中的错误

module.exports = async function badRequest(data) {
  const status = 400;

  if (data.code && data.code === 'E_MISSING_OR_INVALID_PARAMS'){
    return this.res.status(status).json({
      code: 'My code',
      message: 'My message',
      whateva: 'Bla bla'
    });
  }

  return this.res.status(status).json(data);
};

我有一个自定义项目,我需要你要求的同样的东西。我制作了一个 npm 包,它接受一个错误对象并使其对前端更漂亮。像这样的:

module.exports = async function badRequest(data) {

  const formatError = require('myFormatError');
  const {status, response}= formatError(data);

  return this.res.status(status).json(response);

};

它不需要是npm,你可以做一些功能。我希望你正在寻找这个。

【讨论】:

  • 感谢您的努力。您的代码 sn-p 处理得很好。但是,我们可以将这些错误传递回视图吗?如果是,那我们如何才能做到这一点?
  • 当然,你可以在 api/responses/* 中使用return res. view ('pathToView', {error: response});。但是您需要处理视图中的错误对象。我建议您对表单进行一些客户端验证。
【解决方案2】:

使用相同的错误对象显示会出错,因为在生产中技术错误会被 toJson 方法剥离。

处理错误的最佳方法是编写自定义错误。比如

  module.exports = {
    friendlyName: 'Login',

    description: 'Login user.',

    inputs: {
      email: {
        description: 'user email.',
        type: 'string'

      },
      password: {
        description: 'user password.',
        type: 'string'

      }
    },

    exits: {
      success: {
        statusCode: 200,
        responseType: 'view',
      },
      badrequest:{
        statusCode: 400,
        responseType: 'view',
      }
    },

    fn: async function (inputs, exits) {
      try{
       if(!inputs.email || !inputs.password){
       return exits.badrequest({code: 'PARAM_MISSING', message: 'Email/Password is missing'});
       }
        // all good
        return exits.success({/* object containing information realted to success*/});
      }
      catch(e){
         return exists.error(e);
        }
      }

    }
  };

【讨论】:

  • 感谢您的努力,但具有讽刺意味的是代码从不输入fn: async function,它甚至在输入之前就抛出错误。
  • @BlueSuiter 感谢您指出这一点。我能想到的唯一解决方案是删除所需的参数并手动测试它。否则,我认为您必须处理视图本身中的错误和消息。我已经按照它修改了代码。
  • 这意味着提供必需的参数只是为了愚弄开发人员。没用?
  • @BlueSuiter Sails 团队有很多错误的决定。我认为,这仅在您使用它返回 JSON 响应时才有用。作为 API 服务。
猜你喜欢
  • 2016-06-13
  • 1970-01-01
  • 2020-01-06
  • 2019-07-26
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多