在Node.js中验证API输入的最佳实践?

时间:2016-03-21 16:05:38

标签: node.js validation http mobile

我正在开发一个移动应用程序,后端在Node.js.用户几乎只能通过移动应用程序与平台进行交互。作为后端的一部分,我公开了移动应用程序使用的多个API - 例如:用于创建帐户,发送消息,发布图片等的API。

验证API输入的最佳做法是什么?

我的想法是为每个API创建一个模块,其目的是从http请求中提取,清理和验证相关属性。例如,“创建帐户”API将具有关联的AccountCreationRequest模块,其中validate方法将定义所有特定于帐户创建的验证。然后,每个特定的验证都可以由express validatorvalidator等库执行。

exports.AccountCreationRequest = {

  init: function(request) {
    ... extract attributes ...
  },

  sanitizeAndValidate: function() {
    ... use express-validator/validator on
    attributes such as username, email, etc ...
  }, 

  isValid: function() {
    ... return result of validation ...
  }
};

然后,当后端API收到请求时,

var accountCreationRequest = AccountCreationRequest.init(httpRequest);
accountCreationRequest.sanitizeAndValidate();

if (accountCreationRequest.isValid()) {
  ... store in database and notify client of success ...            
} else {
  ... notify client of failure ...
}

我担心N API需要N个请求验证模块。但是,由于每个API都是唯一的,我认为代码重用的机会并不多。

1 个答案:

答案 0 :(得分:2)

如果您使用快递,您可以执行类似

的操作
app.use('/private', function(req, res, next) {
    if (/*some condition to check for authentication*/) {
       next();
    } else { //unauthorized
       res.status(401).send('not authorized, please authenticate');
    }
});

将通过您的身份验证条件过滤/ private路径下的所有内容。如果您愿意,也可以在路径中使用通配符。

相关问题