Angular调用Flask接口下载CSV文件时JSON解析错误排查
问题解决:Angular请求Flask返回CSV时的JSON解析错误
问题根源
SyntaxError: Unexpected token '', ""... is not valid JSON错误的核心原因是Angular的HTTP请求配置错误:你将responseType设置为"blob" as "json",这会强制Angular把返回的CSV文本当作JSON解析,自然触发格式错误。
修复步骤
1. 修正Angular服务的请求配置
把服务中的responseType直接设为'blob',移除不必要的类型转换和泛型声明:
public getFullData(value, id) { let params = new HttpParams(); params = params.append('date', value); params = params.append('id', id); return this.http.get(`${this.baseAPIURL}/api/example/download-data`, { params, responseType: 'blob' }); }
2. 优化组件的订阅逻辑
返回数据已经是Blob类型,无需二次包装,同时改用更可靠的下载触发方式:
fullDownload() { const date = this.selectedDate; const id= this.selectedId; this.seriveFile.getFullData(date, id).subscribe( data => { const url = window.URL.createObjectURL(data); const downloadLink = document.createElement('a'); downloadLink.href = url; downloadLink.download = 'export.csv'; document.body.appendChild(downloadLink); downloadLink.click(); window.URL.revokeObjectURL(url); document.body.removeChild(downloadLink); }, error => { this.errorMessage = error.message || '下载失败'; } ); }
3. Flask端无需修改
你的Flask代码配置正确,返回的响应头和CSV格式符合要求,保持当前代码即可:
resp = make_response(df.to_csv(index=False)) resp.headers["Content-Disposition"] = "attachment; filename=export.csv" resp.headers["Content-Type"] = "text/csv" return resp
额外提示
- 使用创建
<a>标签的方式触发下载,比直接window.open(url)更不容易被浏览器拦截。 - 调用
revokeObjectURL可以释放Blob占用的内存,避免内存泄漏。
内容的提问来源于stack exchange,提问作者LearnerCode
相关产品推荐
相关产品推荐

