[Vuejs]-ExpressJS res.download() on backend + fetch on frontend

0👍

This is how I implemented download on my express application. When a user visits this particular URL, they will automatically download the file. It is a code snippet on a project I was working on. Hope it helps

router.get('/frontliners/file.csv', function (req, res) {
    controller.airtableFrontliners((output) => {
        res.status(200)
        const file = `${__dirname}/data.csv`; // Get the path of the file
        res.download(file); 
    })
});

0👍

The thing that you are missing is the path to the file you are trying to download.

app.get('/download', function (req, res, next) {
    if (req.query.filename) {
        try {
            res.download(req.query.filename); 
        } catch (error) {
            console.log('Unable to read ' + req.query.filename + ' file. Please check');
            res.write('Unable to read ' + req.query.filename + ' file. Please check');
            res.status(501);
        }
        res.end();
    } else {
        next();
    }
});

If we look at your code on the res.download(queryparams.filename) part, You are missing the relative path to the file (also the file extension type if you are not aware) that would be downloaded.

Suppose I hit this URL like: http://.../download/day1.json.
The code would interpret it as res.download("day1.json") right, but it wont know where to look for that file.

So if you change this to res.download("./downloadables/day1.json") the file day1.json will downloaded because the code can navigate to that file which is in the downloadable directory in the root directory of the code.
Making changes like the one given below can help you solve this.

app.get('/download', function (req, res, next) {
    if (req.query.filename) {
        try {
            // Adding ticks for string fomatting
            res.download(`./${req.query.filename}`); 
        } catch (error) {
            console.log('Unable to read ' + queryparams.filename + ' file. Please check');
            res.write('Unable to read ' + queryparams.filename + ' file. Please check');
            res.status(501);
        }
        res.end();
    } else {
        next();
    }
});

Leave a comment