【问题标题】:How to write and download csv file in feathers api?如何在羽毛 api 中编写和下载 csv 文件?
【发布时间】:2017-11-21 06:58:31
【问题描述】:

我正在尝试使用 api 为 csv 文件中的导出数据创建 api,这意味着我想使用羽毛服务下载 csv 文件。

app.service('/csv').hooks({
  before: {
    create: [ function(hook, next) {
        const dataToStore = [
          {
            to: 'marshall',
            from: 'marshall',
            body: 'Stop talking to that rubber ducky!'
          }, {
            to: 'marshall',
            from: 'marshall',
            body: `...unless you're rubber duck debugging.`
          }
        ]
        hook.data = dataToStore;
        next();
      }
    ]
  },
  after: {
    create: [ function(hook,next){
        // here i need imported data to be write in csv and make api side as downloadable 
        // when i hit the service i want to download file in csv file format.
        hook.result.code = 200; 
        next();
      }
    ]
  },
  error: {
    create: [function(hook, next){
      hook.error.errors = { code : hook.error.code };
      hook.error.code = 200;
      next();
    }]
  }
});

【问题讨论】:

    标签: javascript node.js csv export-to-csv feathersjs


    【解决方案1】:

    格式化响应不是在钩子中完成的,而是在 Express 中间件中使用 general custom formatterservice specific middleware 完成的。

    注册/csv服务时添加在末尾(服务调用数据会在res.data中):

    const json2csv = require('json2csv');
    const fields = [ 'to', 'from', 'body' ];
    
    app.use('/csv', createService(), function(req, res) {
      const result = res.data;
      const data = result.data; // will be either `result` as an array or `data` if it is paginated
      const csv = json2csv({ data, fields });
    
      res.type('csv');
      res.end(csv);
    });
    

    【讨论】:

    • 这似乎有变化...在文档中是require('json2csv').parse
    猜你喜欢
    • 2020-11-13
    • 2021-06-12
    • 2019-12-12
    • 2018-08-22
    • 2020-06-20
    • 2018-02-23
    • 2019-12-20
    • 1970-01-01
    • 2013-02-10
    相关资源
    最近更新 更多