【问题标题】:Angular HttpClient HttpErrorResponse Unexpected token in JSON at position 0Angular HttpClient HttpErrorResponse JSON 中位置 0 的意外标记
【发布时间】:2019-05-15 02:47:30
【问题描述】:

我有一个 Angular 7 应用程序 POST-ing 一个 excel 文件,并期望从我的 Express 服务器返回一个 excel 文件,如下所示:

myAngular.service.ts

const url = 'myEndpoint';
const formData: FormData = new FormData();
formData.append('xlsx', postedExcelFile, 'myFilename');
const httpOptions = {
headers: new HttpHeaders({
    responseType: 'blob'
  })
};
return this.http.post(url, formData, httpOptions);

这里是来自 Express 服务器发送文件的代码:

server.js

res.download(pathToMyFile);

在前端,响应是 HttpErrorResponse 并且错误状态:

SyntaxError: Unexpected token P in JSON at position 0

我可以看到错误文本的内容是Excel文件的内容,这意味着该文件确实正在被发送回浏览器。但是,出于某种原因,Angular 似乎期待 JSON 并尝试解析它。

如您所见,我已将 responseType: 'blob' 标头添加到 POST 请求中,以便它可以期待返回文件,但我仍然收到此错误。是否有什么我忘记添加到发布请求的内容?

【问题讨论】:

    标签: angular express file-upload httprequest blob


    【解决方案1】:

    headers 中没有响应类型

    将它们发送为:

    this.http.post(url, formData,  {headers: yourHeaders, responseType: 'blob'});
    

    【讨论】:

    • 啊我知道我做错了什么,我改变了它,我得到了 blob 但到目前为止我只有 console.logged 响应数据。如何让浏览器启动文件下载?
    • @Moose 我今天回答了这个问题,你可能想看看。 stackoverflow.com/questions/53758280/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 2020-10-31
    • 2018-04-21
    • 2018-08-29
    • 1970-01-01
    • 2019-03-19
    相关资源
    最近更新 更多