【问题标题】:Express - How to serve a CSV from a remote server?Express - 如何从远程服务器提供 CSV?
【发布时间】:2019-11-07 19:38:25
【问题描述】:

我有一个带有一条路由的简单节点/快速 API。在这条路线中,我想向发回 CSV 的第 3 方服务发出 API 请求。反过来,我想将该 CSV 作为响应发送。

我有这个,但感觉可能缺少一些基本的东西:

//get csv from remote server
let csv = await axios.get('https://api.com/csv', {
    responseType: 'blob'
})
//serve that csv as a response
res.send(csv)

【问题讨论】:

    标签: node.js express axios


    【解决方案1】:

    你必须像这样使用axios。

        axios.get('https://api.com/csv', {
          responseType: 'blob'
         })
          .then(function (response) {
            // handle success
            res.send(response);
          })
    

    更多信息请参考https://www.npmjs.com/package/axios

    【讨论】:

    • 我的错我忘了添加等待。问题是使用 async-await 和 promises 我都得到“TypeError:将循环结构转换为 JSON”
    • 根据您的错误,您不能直接发送API响应,因为响应具有一些原型功能,并且在使用 res.send 时会尝试将数据转换为json。
    【解决方案2】:

    您可以将管道用于 httpStream。如果文件大小很大,这样会非常快。这是使用 nodejs 内置的 http 模块。希望这会对你有所帮助。

    app.get('/path',(req,res)=>{
    var options = {
        hostname: 'hostname',
        port: 80,
        path: '/path',
        method: 'GET',
        headers: {
    
        }
      };
    
      var req = http.request(options, (response) => {
    
        response.pipe(res).on('error',(error)=>{
            console.log('Error');
        });
      });
    
      req.on('error', (e) => {
        console.error(`problem with request: ${e.message}`);
      });
      req.end();
    });
    

    【讨论】:

      猜你喜欢
      • 2012-06-15
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多