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

标签 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 都是唯一的,我认为代码重用的机会不大。

最佳答案

如果你使用 express,你可以做类似的事情

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 路径下的所有内容。如果愿意,您也可以在路径中使用通配符。

关于node.js - 在 Node.js 中验证 API 输入的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36136061/

相关文章:

regex - Html5 模式,检查至少 2 位数字和至少 4 个任意顺序的字母

用于密码验证的php

python - 当请求方法不是 POST 或 PUT 时,网络服务器是否应该忽略请求主体?

javascript - 如何以 Angular 获取响应 header

javascript - Node.js 从 do while 循环中调用异步函数

asp.net-mvc - jqGrid & MVC3 - 添加模型验证

node.js - 如何在 Keystone.js 数据库 ODM 中创建字符串数组?

http - 是否有将对象序列化为 HTTP 内容类型 "application/x-www-form-urlencoded"的实用程序?

javascript - Nodejs 数据字段中的响应数据发送给谁

node.js - 如何在sequelize(nodejs orm)中服务器端过滤表的每个字段