node.js - 使用 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 在....
解决方案
默认情况下,使用 HttpClient 发出的请求被认为具有 JSON 响应。
要获取 CSV,您可以使用强制文本响应
downloadCSV(id: string) {
return this.httpService.get(`/xxxx/get/${id}/download`, {responseType: 'text'});
}
您还可以阅读这部分文档:https ://angular.io/api/common/http/HttpRequest#responseType
推荐阅读
- python - 使用 JiTCODE 的 Lyapunov 指数
- javascript - CSS 和 JS 查询
- eslint - Prettier 和 ESLint 冲突使用带有 Comma dangle 的 airbnb 风格指南
- gatsby - 同时从 Markdown 和 JSON 中获取博客文章的数据
- sql - Postgres 解决由破折号 (-) 引起的语法错误
- json - 如何在 Laravel 中使用 Api 从两个表中获取所有记录
- django - 单击提交按钮后未添加评论
- javascript - 我正在尝试使用 jquery toggle 在文本和图像之间交换
- android - 附加 Firebase 令牌以启动 URL -Trusted Web 活动
- vim - 一个简单的解决方案,我可以使用 Vim 将 3 行文本连接/连接在一起