使用 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/服务更改为HttpClient,但它不起作用,因为我在使用HTTPServices的当前API调用中还有另一个API调用。

3)将其更改为我可以附加{responseType:"blob"作为"json"}的post方法,但它不起作用,无论如何它应该作为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,它也说

语法错误:JSON 中位置 0 处出现意外的标记 N at JSON.parse () at XMLHttpRequest.onLoad (http://localhost:8080/vendor.js:22263:51) 在。。。。

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

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

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

最新更新