Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular HttpClient HttpErrorResponse Unexpected token in JSON at position 0

I have an angular 7 app POST-ing an excel file and expecting an excel file back from my Express server, like so:

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);

Here is the code from the Express server that is sending the file:

server.js

res.download(pathToMyFile);

On the front end, the response is an HttpErrorResponse and the error states:

SyntaxError: Unexpected token P in JSON at position 0

I can see that the content of the error text is the contents of the Excel file, which means the file is indeed being sent back to the browser. But, for some reason, Angular seems to be expecting JSON and attempts to parse it.

As you can see, I have added the responseType: 'blob' header to the POST request so that it can expect a file back, but I still get this error. Is there something I am forgetting to add to the post request?

like image 701
Moose Avatar asked Jan 28 '23 00:01

Moose


1 Answers

Response type doesn't go in headers

Send them as:

this.http.post(url, formData,  {headers: yourHeaders, responseType: 'blob'});
like image 143
Ashish Ranjan Avatar answered Jan 29 '23 21:01

Ashish Ranjan