首页 > 解决方案 > 后端的 ExpressJS res.download() + 前端的 fetch

问题描述

对不起,如果这是一个菜鸟问题,但我无法让它工作......

我有一个使用 NodeJS 和 ExpressJs 并提供一些使用 VueJS 构建的静态内容的后端。

我想允许用户下载文件,所以我正在尝试实现它。

在后端,这是代码

    app.get('/download', function (req, res, next) {
    let queryparams = req.query;
    if (queryparams.filename) {
        try {
            res.download(queryparams.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();
    }
});

在前端,我尝试使用 downloadjs npm 包,但它不起作用,而且,我需要它吗?

fetch(`https://${servername}/download?filename=` + data.filename)
    .then((response) => response.blob())
    .then((blob) => downloadjs(blob, data.filename));

任何帮助将不胜感激

鲍勃

标签: node.jsexpressvue.js

解决方案


这就是我在我的 express 应用程序上实现下载的方式。当用户访问此特定 URL 时,他们将自动下载该文件。这是我正在从事的项目的代码片段。希望能帮助到你

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

推荐阅读