【发布时间】:2019-04-02 16:59:51
【问题描述】:
我在 NodeJS 中截取了代码以尝试从我的服务器下载。
router.post("/download", function(req, res, next) {
console.log(req);
filepath = path.join(__dirname, "/files") + "/" + req.body.filename;
console.log(filepath);
res.sendFile(filepath);
});
这是我的 Angular 2 代码: Component.ts
download(index) {
var filename = this.attachmentList[index].uploadname;
this._uploadService
.downloadFile(filename)
.subscribe(data => saveAs(data, filename), error => console.log(error));
}
Service.ts
export class UploadService {
constructor(private http: HttpClient, private loginService: LoginService) {}
httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
responseType: "blob"
})
};
downloadFile(file: string): Observable<Blob> {
var body = { filename: file };
console.log(body);
return this.http.post<Blob>(
"http://localhost:8080/download",
body,
this.httpOptions
);
}
在我的 HTML 响应中,我将文件正确记录到浏览器的网络检查工具中。然而 Angular 正在尝试将响应解析为 JSON 对象,这显然不起作用,因为响应是一个 blob。
我得到的错误是这样的:
JSON.parse() 中位置 0 处的 JSON 中的意外标记 % 在 XMLHttpRequest.onLoad 角度 2
有人对此有解决方案吗?
提前致谢!
【问题讨论】:
-
您已将
responseType添加为标头,但不应如此。它应该只是在httpOptions对象内,而不是headers对象内 -
@user184994 它在开始时工作,但是当我重新编译时它给了我一个编译错误。 “ src/app/services/upload.service.ts(25,7) 中的错误:错误 TS2345:类型为 '{ headers: HttpHeaders; responseType: string; }' 的参数不可分配给类型为 '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'。属性 'responseType' 的类型不兼容。类型 'string' 不可分配给输入'"json"'。"