【问题标题】:How to download a CSV with the information of an external JSON in Node JS?如何在 Node JS 中下载包含外部 JSON 信息的 CSV?
【发布时间】:2021-06-06 12:51:50
【问题描述】:

我开始使用Node JS 进行开发,我正在创建一个应用程序来实现以下目标:

下载包含在 API 中找到的 JSON 信息的 CSV。我有一个内部文件,其中包含 JSON 所在的 url,我需要从该 url 中提取信息并将其下载为 CSV。我正在使用json-2-csvnode-fetchfs 模块。

我的问题:我无法访问 JSON 中包含的信息来下载它

这是我的controller

import { Request, Response } from 'express';
const converter = require("json-2-csv");
const fetch = require("node-fetch");
const fs = require("fs");

class IndexController {
  public async index(req: Request, res: Response) {
  const api =req.query.api; //api1
  const url = conf.API_MOCS[`${api}`].url; //url containing the json
  const getJson = async () => {
        const response = await fetch(url);
        const responseJson = await response.json();
        return responseJson;
    };
  }
}

export const indexController = new IndexController(); 

【问题讨论】:

  • I cannot access the information contained in the JSON to download it 是什么意思? responseJson 未定义吗?拨打getJson时是否有错误?
  • 您看到了什么错误?提供的内容不足以调试问题?无法访问信息是什么意思?此外,getJson 变量是一个函数,因此请确保您也处理它(它是异步的,因此请确保您等待结果)/
  • @eol 我的问题是我不知道如何遵循,我只找到从其他文件转换内部 JSON 的信息,但我不知道如何从 api 中做到这一点
  • 我明白了 - 检查我的答案。

标签: node.js typescript api json2csv


【解决方案1】:

问题是你永远不会调用你的getJson 函数,即缺少像const jsonResponse = await getJson() 这样的调用。不过,实际上没有必要在单独的函数中执行此操作。得到json后,需要将其传递给csv-converter,最后通过res-object发送响应。

这是一个简化的示例(仍需要错误处理),它从假的 rest-api 获取 json 并将其转换为 csv 并允许用户下载:

const express = require("express");
const app = express();
const port = 3000;

const converter = require("json-2-csv");
const fetch = require("node-fetch");

app.get("/", async (req, res) => {
  const url = "https://jsonplaceholder.typicode.com/users";
  const response = await fetch(url);
  const jsonResponse = await response.json();

  const csvString = await converter.json2csvAsync(jsonResponse);
  res.setHeader("Content-disposition", "attachment; filename=data.csv");
  res.set("Content-Type", "text/csv");
  res.status(200).send(csvString);
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

【讨论】:

  • 好的,我明白了这个问题,现在它可以工作了。是否可以下载具有行数限制的 CSV 并定义一些标题?
  • 当然可以,但问题完全不同。请发布一个带有一些代码的新代码,在其中显示您尝试过的内容。另外,如果此答案解决了您的问题,请单击左侧的复选标记接受它 - 谢谢。
  • 对不起,我一直在更改所有代码以重构它。您从异步中放入的内容会拾取它,但我无法使其正常工作。我要创建另一个问题,你能帮我吗?我接受这个
  • 我的另一个问题是:Download csv in Node JS with async / await。你能帮我解决这个问题吗,这会很有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-12
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
  • 2017-10-21
  • 2019-01-01
  • 2019-01-31
相关资源
最近更新 更多