将http响应从节点映射到json文件

我正在研究一个解决scheme,其中Web服务器(具有express的节点)将使用请求包从Web API获取数据。 数据返回(如果包含validation错误状态码),将再次匹配该值并返回相应的错误消息。 怎么可能实现?

这将是这样的:

var options = { method: 'POST', url: 'apiUrl' } var response = function (error, response, body) { if(!error && response.statusCode == 200){ res.jsonp(body); } else { if (body.language == 'en') { // map the reponse body error status code to en.json } else if (body.language == 'jp') // map the response body error status code to jp.json } } request({ options, response }) 

validation错误的默认主体响应

 { 'language': 'en', 'error': [{ 'ErrorCode': '1000', 'ErrorCode': '1001'}] } 

最终机构响应(处理后)

 { 'language': 'en', 'error': [{'ErrorMessage': 'Invalid data format', 'ErrorMessage': 'Invalid Password'}] } 

用于不同validation语言的资源文件(在服务器中是静态的)

en.json

 { '1000': 'Invalid date format', '1001': 'Invalid password', '1002': ... '1003': ... ... '1999': ... } 

jp.json

 { '1000': 'japan translation', '1001': 'japan translation 2', '1002': ... '1003': ... ... '1999': ... } 

在这里你看到如何。 我正在使用fs模块来打开JSON文件。 而我正在使用maperrorCode数组转换为errorMessage数组

 var response = function(error, response, body) { if (!error && response.statusCode == 200) { res.jsonp(body); } else { // Set defaut language. if (!body.language.match(/en|jp|iw/)) body.language = 'en' // You must specify default language for security reasons. // Open the file, and convert to JSON object var j = JSON.parse( require('fs').readFileSync(__dirname + '/' + body.language + '.json') ) res.jsonp({ language: body.language, // Convert error:[{errorCode}] array to the messages from the JSON error: body.error.map(function(v) { return j[v.ErrorCode] }) }) } }