首页 > 解决方案 > 使用 HttpService 导出为 CSV:JSON 中的意外令牌 N

问题描述

目前,我正在尝试使用 nodejs 作为后端和 angular 作为前端来导出 csv。

我知道错误“JSON 中的意外令牌 N”意味着存在 JSON 解析错误。这意味着我需要将 {responseType: "blob" 更改为 "json"}。但是有一个问题,因为我不能将这些包含在 httpServices 的参数中,因为它只接受 HttpParams 作为参数

因此,关于这一点,我已经尝试过这些

1)return this.httpService.get(`/chatbots/get/${id}/download`, {responseType: 'text'})返回一个错误,因为 httpService 只接受 HttpParams 作为参数

2) 将 HttpServices 从 @core/services 更改为 HttpClient 但它不起作用,因为我在当前 API 调用中有另一个使用 HTTPServices 的 API 调用。

3) 将其更改为 post 方法,我可以在其中附加 {responseType: "blob" as "json"} 但它不起作用,无论如何它应该作为 get 工作?

目前,输出已经在 csv 中显示了文本。

router.get('/get/:id/download', passport.authenticate('jwt', {
  session: false
}), (req, res, next) => {
   ..... 
   console.log(output) 
   res.attachment('test.csv')
   res.send(output)
}

在服务方面:

import { HttpService } from '../../@core/services';
constructor(
      private httpService: HttpService, ) {}
...
 downloadCSV(id: string) {
      return this.httpService.get(`/xxxx/get/${id}/download`)
   }

在组件中

  export() {
    if (this.id) {
      this.chatbotService.downloadChatbot(this.id)
      .subscribe((data: any) => {
        const blob = new Blob([data], { type: 'text/csv' });
        const fileName = `${this.id}-test.csv`;
        saveAs(blob, fileName);
    })
    }
  }

即使状态是 200,它说

SyntaxError:在 XMLHttpRequest.onLoad ( http://localhost:8080/vendor.js:22263:51 )的 JSON.parse () 的位置 0 处的 JSON 中的意外标记 N 在....

标签: node.jsangular

解决方案


默认情况下,使用 HttpClient 发出的请求被认为具有 JSON 响应。
要获取 CSV,您可以使用强制文本响应

downloadCSV(id: string) {
  return this.httpService.get(`/xxxx/get/${id}/download`, {responseType: 'text'});
}

您还可以阅读这部分文档:https ://angular.io/api/common/http/HttpRequest#responseType


推荐阅读