In my application I create a file on the backend, and I wish then to deliver that to the user via a browser download. I have tried numerous
Here is the express backend:
app.get('/download', (req, res) => {
res.download('filename.txt', function (err) {
console.log(err);
});
})
The console call isn't returning, so presumably no error. Here is what I am doing in the front-end, following advice here and here:
window.open('localhost:3000/download');
The result is that I get a blank window popping up, but no download. I have also tried this:
const filePath = 'localhost:3000/download/';
const link = document.createElement('a');
link.href = filePath;
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();
But in this case, nothing happens.
What am i doing wrong? I at a loss even how to debug any further.
Update 1
Thanks @jal_a, I've made progress. I realise now that if I manually create a window and enter the url (as suggested) the download works. However, when the window is launched from the application using window.open(url)
where url is the same, the window opens but the download doesn't initiate. If I then go to the created window, click in the url and press return ... voila! It works! How can I make the download initiate from the application launched window?
Update 2
Thanks @IceMetalPunk, I tried that and I'm getting the following error in the console - the file I'm trying to download is gps data in gpx format - which I can see in the response, but it seems to be expecting JSON?? Do I need to do any pre-processing to send a file?:
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK",
url: "http://localhost:3000/download/", ok: false, …}
error:
error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse
...
text: "<?xml version="1.0" encoding="UTF-8"?>
↵<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/0">
↵ <rte>
↵ <name>undefined</name>
↵ <rtept lat="50.70373" lon="-3.07241" />
↵ <rtept lat="50.70348" lon="-3.07237" />
↵ </rte>
↵</gpx>"
__proto__: Object
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit:
ƒ}
message: "Http failure during parsing for http://localhost:3000/download/"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:3000/download/"
__proto__: HttpResponseBase