【问题标题】:Sails js beforeCreate next() callbackSails js beforeCreate next() 回调
【发布时间】:2016-10-07 07:11:04
【问题描述】:

我正在为我的 Web 应用程序使用sails js。我必须更改 beforeCreate 的默认行为。先看代码:

beforeCreate: function(values, next) {

    //ParamsCheck is my service and 'check' is method which will validate the
    //parameters and if any invalid parameter then error will be thrown, otherwise 
    //no error will be thrown

    ParamsCheck.check(values)
   .then(() => {
     // All Params are valid and no error
     next();
   })
   .catch((err) => {
     //Some errors in params, and error is thrown
     next(err);
   });
}

所以,问题是如果有任何错误,那么下一个方法会自动重定向到 serverError,错误代码为 500,而我想用我的自定义响应重定向它(例如:badRequest,错误代码 400)。如何做到这一点?

【问题讨论】:

  • 收到此错误后如何发送响应,能否显示调用最终回调的代码?
  • 其实在sails中,如果给beforeCreate方法的next()回调传入任何参数,就会报错,报500错误。 'next()' 是最后的回调。我想更改默认响应。
  • 当你传递错误时会回调,它会给你500 statusCode。对于错误的请求意味着statusCode:400你需要在响应客户端时传递

标签: node.js sails.js


【解决方案1】:

您正在beforeCreate 中执行某种验证。但是,这不是验证的正确位置。

更好的方法是使用此处描述的自定义验证规则http://sailsjs.org/documentation/concepts/models-and-orm/validations#?custom-validation-rules 或创建一个策略来处理验证。

我喜欢使用政策:

module.exports = function(req, res, next) {
    var values = req.body;
    ParamsCheck.check(values).then(() => {
     return next();
   }).catch((err) => {
     return res.send(422); // entity could not be processed
   });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 2020-11-30
    • 2015-10-03
    相关资源
    最近更新 更多