0

SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse

I want to download excel through api ..i tried this method but unfortunately im getting this error

SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://localhost:5002/vendor.js:28768:51)

my Code here

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);
}
3
  • Obviously, the response data is not JSON. Could you please show what the server response is? Your localhost is not accessible over the Internet. Commented Apr 3, 2019 at 10:01
  • my response data is excel : application/vnd.ms-excel Commented Apr 3, 2019 at 10:05
  • And what is the code of your http.post method? Commented Apr 3, 2019 at 10:34

1 Answer 1

1

Remove the CORS headers and make responseType an option, not a header:

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'
    })
}

CORS headers are response headers, not request headers.

The responseType is an XHR option, not a header.

For more information, see

Sign up to request clarification or add additional context in comments.

1 Comment

For the visual studio code users: this solution might give you an error, ignore it and update your TSLint. This solution works fine but somehow older versions of TSLint will give you an error whilst applying this solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.