【问题标题】:Why does my csv file which I'm downloading from my node.js backend not contain csv data?为什么我从 node.js 后端下载的 csv 文件不包含 csv 数据?
【发布时间】:2021-01-30 11:04:42
【问题描述】:

我在后端有一个带有 node.js 的 vue.js 应用程序。我正在尝试在后端构建一个 csv 文件并将其作为文件下载发送到前端。它不工作。

这是我从后端返回的内容:

来自ListingController.getListingsCSV():

async getListingsCSV(user, listingIds) {

/* convert listings to csv string. This is working. */

      return {
        body: headersString + "/n" + csvString,
        type: "text/csv",
        filename: "listing.csv"
      };
}

headersString 是逗号分隔的标题列表,csvString 是逗号分隔的值列表。

然后在处理所有请求的 index.js 中,我返回这个:

if (rh.match(event, "GET", "/listings/csv")) {
      const res = await require("./listings/ListingController").getListingsCSV(
        user,
        qParams.listingIds.split(",")
      );
      return new HttpResponse(
        200,
        res.toString("base64"),
        { "content-type": "text/csv" },
        true
      );
}

在前端,我有这个:

      window.open(
        `/api/listings/csv?listingIds=${this.listingId}`,
        "_blank"
      );

当我触发下载时,我得到一个文件,其内容如下:

¡¸ÞrÓ›ç-

我不知道那是什么。这绝对不是我期待的 CSV。此外,它似乎忽略了我给它的文件名:“listing.csv”并将其命名为“csv”(无扩展名)。

前端和后端都不会在日志中显示任何错误。 Chrome 和 Firefox 中的网络选项卡仅显示 200 个状态代码。

这里会发生什么?

【问题讨论】:

    标签: node.js csv vue.js download


    【解决方案1】:

    解决方案是返回这个:

          return new HttpResponse(
            200,
            res.body,
            {
              "content-type": res.type,
              "content-disposition": `attachment; filename="${res.filename}"`
            },
            false
          );
    

    首先,我将从 getListingCSV() 返回的整个对象作为 HttpResponse 的主体返回。我把它改成了 res.body。

    其次,我删除了 base 64 编码,因为这根本没有必要。

    第三,我添加了 content-disposition 来适当地设置文件名。

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-12
      相关资源
      最近更新 更多