2016-03-21 33 views
1

我正在开发一个移动应用程序,后端在Node.js中。用户将几乎全部通过移动应用程序与平台进行交互。作为后端的一部分,我公开了多个API供移动应用程序使用 - 例如:API创建帐户,发送消息,发布图片等。在Node.js中验证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都是唯一的,我不认为代码重用的机会很多。

回答

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'); 
    } 
}); 

将通过您的认证条件过滤/私人路径下的一切。如果您愿意,也可以在路径中使用通配符。