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?
Response type doesn't go in headers
Send them as:
this.http.post(url, formData, {headers: yourHeaders, responseType: 'blob'});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With