Angular HttpClient-如何请求非JSON数据 SyntaxError:JSON.parse位置0处的JSON中意外的标记P

Angular HttpClient-如何请求非JSON数据 SyntaxError:JSON.parse位置0处的JSON中意外的标记P,angular,typescript,Angular,Typescript,我想通过api下载excel。我尝试了这个方法,但不幸的是我遇到了这个错误 SyntaxError:XMLHttpRequest.onLoad()的JSON.parse()位置0处的JSON中出现意外标记p 我的代码在这里 getSalesARExcel(attach: string): Observable<any>{ const obj={ "AttachmentId":attach } return this.http.post(base

我想通过api下载excel。我尝试了这个方法,但不幸的是我遇到了这个错误

SyntaxError:XMLHttpRequest.onLoad()的JSON.parse()位置0处的JSON中出现意外标记p

我的代码在这里

getSalesARExcel(attach: string): Observable<any>{
    const obj={
        "AttachmentId":attach
    }
    return this.http.post(baseUrl + 'api/report/aging/receivables/summary/download/xlsx', obj ,{
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            "Authorization":'Bearer ' + localStorage.getItem('token'),
            'Access-Control-Allow-Origin':'*',
            'Access-Control-Allow-Headers':'Origin, Methods, Content-Type',
            'responseType': 'ResponseContentType.Blob'
        })
    })
}

this.excel.getSalesARExcel(value.attach).subscribe(res => {
    console.log("excel", res)
    this.downloadExcelFile(res);
})

downloadExcelFile(data: any){
    var blob = new Blob([data], { type: 'application/vnd.ms-excel' });
    var url= window.URL.createObjectURL(blob);
    window.open(url);
}
getSalesARExcel(附加:字符串):可观察{
常数obj={
“AttachmentId”:附加
}
返回此.http.post(baseUrl+'api/report/aging/Responses/summary/download/xlsx',obj{
标题:新的HttpHeaders({
“内容类型”:“应用程序/json”,
“授权”:“持有者”+localStorage.getItem('token'),
“访问控制允许来源”:“*”,
“访问控制允许标头”:“来源、方法、内容类型”,
“responseType”:“ResponseContentType.Blob”
})
})
}
this.excel.getSalesARExcel(value.attach).subscribe(res=>{
console.log(“excel”,res)
此.downloadExcelFile(res);
})
下载Excel文件(数据:任意){
var blob=new blob([data],{type:'application/vnd.ms excel'});
var url=window.url.createObjectURL(blob);
窗口打开(url);
}

删除CORS标题,并将
响应类型设置为选项,而不是标题:

getSalesARExcel(attach: string): Observable<any>{
    const obj={
        "AttachmentId":attach
    }
    return this.http.post(url, obj ,{
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            "Authorization":'Bearer ' + localStorage.getItem('token'),
            ̶'̶A̶c̶c̶e̶s̶s̶-̶C̶o̶n̶t̶r̶o̶l̶-̶A̶l̶l̶o̶w̶-̶O̶r̶i̶g̶i̶n̶'̶:̶'̶*̶'̶,̶
            ̶'̶A̶c̶c̶e̶s̶s̶-̶C̶o̶n̶t̶r̶o̶l̶-̶A̶l̶l̶o̶w̶-̶H̶e̶a̶d̶e̶r̶s̶'̶:̶'̶O̶r̶i̶g̶i̶n̶,̶ ̶M̶e̶t̶h̶o̶d̶s̶,̶ ̶C̶o̶n̶t̶e̶n̶t̶-̶T̶y̶p̶e̶'̶,̶
            ̶'̶r̶e̶s̶p̶o̶n̶s̶e̶T̶y̶p̶e̶'̶:̶ ̶'̶R̶e̶s̶p̶o̶n̶s̶e̶C̶o̶n̶t̶e̶n̶t̶T̶y̶p̶e̶.̶B̶l̶o̶b̶'̶
        }),
        'responseType': 'blob'
    })
}
getSalesARExcel(附加:字符串):可观察

  • 显然,响应数据不是JSON。你能告诉我服务器的响应是什么吗?您的本地主机无法通过Internet访问。我的响应数据是excel:application/vnd.ms-excel。您的
    http.post
    方法的代码是什么?对于visual studio代码用户:此解决方案可能会给您一个错误,请忽略它并更新您的TSLint。此解决方案工作正常,但旧版本的TSLint在应用此解决方案时会出现错误。