【问题标题】:Mapping http response from node to json file将节点的 http 响应映射到 json 文件
【发布时间】:2016-05-14 06:22:35
【问题描述】:

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

应该是这样的:

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

验证错误的默认正文响应

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

最终的身体反应(处理后)

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

不同验证语言的资源文件(服务器中的静态)

en.json

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

jp.json

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

【问题讨论】:

  • 您的响应不是有效的 JSON,ErrorCode 键重复,您的意思是 [{ 'ErrorCode': '1000' }, {'ErrorCode': '1001'}]

标签: json node.js express


【解决方案1】:

在这里您可以了解如何操作。 我正在使用 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]
            })
        })
    }
}

【讨论】:

  • 您可以将var j = JSON.parse(require('fs').readFileSync(__dirname + '/' + body.language + '.json')) 替换为var j = require(__dirname + '/' + body.language + '.json')
  • 好主意。你确定它没有被破坏吗?
  • 据我所知,我一直都在使用它 :) 你甚至不需要 .json 扩展,require 就很好。
  • @Amina 假设每个请求都会读取该文件,这是否会带来任何重大的性能问题。另外,readfilesync 不会锁定整个 Web 服务器以防止任何其他请求处理吗?
猜你喜欢
  • 2020-02-05
  • 2011-01-10
  • 2020-09-13
  • 2020-08-08
  • 2023-03-10
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多