【问题标题】:Passing JSON object in HTTP request在 HTTP 请求中传递 JSON 对象
【发布时间】:2016-07-24 14:53:36
【问题描述】:

我有以下几点:

路由文件“prontuarios.js”:

     module.exports = function(app){        
        getProntuarios =  function(request, response, next){
            var sqlCustom = request.query;  
            var connection = app.infra.connectionFactory();
            var prontuariosDAO = new app.infra.ProntuariosDAO(connection);
            prontuariosDAO.lista(sqlCustom, function(erros, resultados){            
                if(erros){
                    return next(erros);
                }
                response.format({
                    json: function(){
                        response.json(resultados);
                    }
                });
            });
            connection.end();       
        } 

        app.route('/v1/prontuarios')
            .get(getProntuarios);
... 

和 DAO 文件“ProntuariosDAO.js”

...
ProntuariosDAO.prototype.lista = function(sqlCustom, callback){
    var _sqlCustom;
    console.log(`sqlCustom ${sqlCustom}`);      
    if (sqlCustom){
        _sqlCustom = sqlCustom; 
    }
...

当我调用prontuariosDAO.lista函数时,我希望传递“sqlCustom”参数,但问题是“sqlCustom”必须是函数ProntuariosDAO.prototype.lista中的JSON对象。但是它没有发生,sqlCustom 参数变成了这样的字符串:

{ 
    limit: '10',
    offset: '2',
    orderBy: '{"field":"nome","type":"desc"}',
    whereAnd:
       [ 
         '{"field":"id","operator":"<","value":"300"}',
         '{"field":"nome","operator":"like","value":"jo%"}' 
       ] 
}

我曾尝试使用JSON.parse 函数,但它无法正常工作,因为它会将orderBywhereAnd 像字符串一样解析。

这是一种将字符串转换为 JSON 的方法吗?我是否正确传递了 HTTP 参数?

【问题讨论】:

    标签: json node.js http


    【解决方案1】:

    看起来您需要递归应用 JSON.parse 以获取返回给您的数据:

    data = { 
        limit: '10',
        offset: '2',
        orderBy: '{"field":"nome","type":"desc"}',
        whereAnd:
           [ 
             '{"field":"id","operator":"<","value":"300"}',
             '{"field":"nome","operator":"like","value":"jo%"}' 
           ] 
    }
    JSON.parse(data.orderBy)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-24
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多