【问题标题】:Parse res.text Node express解析 res.text 节点表达
【发布时间】:2021-06-29 23:18:26
【问题描述】:

我正在从基于云的存储中检索作为 res.text 的 csv 文件,需要将其转换为 json。

我想知道是否应该在 fetchUrl 的返回中进行解析,还是应该在路由 (res.send) 中进行解析?

const fetchUrl = async () => {
  const URL_1 = 'https://file.csv'
  const res = await fetch(URL_1)
  return res.text()
}

router.get('/data', async (req, res, next) => {
  try {
      const getAllData = await fetchUrl();
      console.log(getAllData, 'fetching?');
      res.send(getAllData);
  } catch (err) {
    next(err);
    //res.send({ message: err })
    // res.status(404).send(err)
    console.log(err)
  }
})

【问题讨论】:

    标签: node.js json express fetch


    【解决方案1】:

    我使用了一个自定义函数,将其转换为第二个 .then 中的 json。这样我就不必在每次调用端点时都获取数据,因为数据不会改变。 像这样:

    let getAllData 
    
    fetch('https://file.csv')
      .then(res => res.text())
      .then(data => {
        getAllData = csvToJSON(data)
        getAllData.forEach((item) => {
          item.startTime = new Date(item.startTime)
        })
      })
    

    【讨论】:

      猜你喜欢
      • 2013-03-28
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 2021-02-08
      相关资源
      最近更新 更多