【问题标题】:Loopback - Return queried data as CSV file to browserLoopback - 将查询到的数据作为 CSV 文件返回到浏览器
【发布时间】:2018-12-29 05:20:49
【问题描述】:

我正在查询一个数据库表,并希望这个数据集以 CSV 格式返回给浏览器,即在浏览器中它应该像下载文件一样。

以下是我到目前为止所做的远程方法。不知道如何实施以及缺少什么。

Person.remoteMethod(
      'exportPersons',
        {
  http: {path: '/exportPersons', verb: 'get'},
  returns: [
    {arg: 'Content-Type', type: 'application/octet-stream', http: { target: 'header' }}
  ]
}
      );

Person.exportRoutes = function (cb) {

              Person.find({}, function(err, data) {

                var fields = ['id', 'name'];

                // I'm using json2csv package
                json2csv({ data: JSON.stringify(data), fields: fields }, function(err, csv) {
                  cb(null, csv);    
                });

              });     
           }

我收到此错误 TypeError:标头内容包含无效字符

请大家帮忙!!!

【问题讨论】:

    标签: node.js loopbackjs loopback


    【解决方案1】:

    如果您打算返回 json,这就是它的工作原理:

    //in model.json or when we register remote method
    returns : [
    { arg: "first_property", "type" : "string"}, //first_property will be a key name
    { arg: "second_property", "type" : "string"}
    ]
    
    //in remote method function when we run callback
    cb( null, //error?
    first_property_value, 
    second_property_value
    )
    

    如果您打算返回非 JSON 结果并自定义响应标头,则应该是这样:

    //in model.json or when we register remote method
    returns : [
            {"type": "string", "root": true}, //doesnt need key name
            {"arg": "Content-Type", "type": "string", "http": { "target": "header" }}, // assign the value later in the callback's third arguments
    ]
    
    //in remote method function when we run callback
    cb( null, //error?
    string_data, 
    'application/octet-stream' // value for Content-Type header
    )
    

    注意:环回 3.x

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多