环回-将查询的数据作为CSV文件返回到浏览器 [英] Loopback - Return queried data as CSV file to browser

查看:29
本文介绍了环回-将查询的数据作为CSV文件返回到浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查询数据库表,并希望将此数据集以CSV格式返回给浏览器,即在浏览器中就像下载文件一样.

I'm querying a database table and want this dataset to be returned back to browser in CSV format i.e. in browser it should be like downloading file.

以下是我到目前为止已完成的远程方法.不知道如何实现以及缺少什么.

Following is my remote method which I've done so far. Don't know how to implement and what's missing.

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:标头内容包含无效字符

请提供任何帮助!

推荐答案

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

This is how it works if you intended to return 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结果并自定义响应标头,则应该这样:

And this is how it should be if you intended to return non-JSON result, and customize the response header:

//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

这篇关于环回-将查询的数据作为CSV文件返回到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆