【问题标题】:Download JSON file from a node express server through my frontend通过我的前端从节点快速服务器下载 JSON 文件
【发布时间】:2021-07-01 02:34:23
【问题描述】:

我已将文件上传到我的项目目录中的下载文件夹后存储。 我想从前端下载该保存的文件。 当我点击下载按钮时,它不会获取文件。

当我在 express 应用上转到 http://localhost:5000/download 时,我收到了此错误消息

错误:发送后无法设置标头。

Express 服务器代码:

app.get('/download', (req, res) => {
    res.send('file downloaded')
    const file = './downloads/output.yml';
    res.download(file, 'openapi.yml', (err) => {
        if (err) {
            console.log(err)
        } else {
            console.log('file downloaded')
        }
    });
});

前端应用代码:

HTML:

<button class="download-btn">download</button>

脚本:

const handleDownload = async () => {
    const res = await fetch("https://cors-anywhere.herokuapp.com/http://localhost:5000/download");
    const blob = await res.blob();
    download(blob, 'output.yml');
}

downloadBtn.addEventListener('click', handleDownload);

文件夹结构:

更新: 服务器.js

const uploadFiles = async (req, res) => {
    const file = await req.files[0];
    console.log(file)
    postmanCollection = file.path;
    outputFile = `downloads/${file.filename}.yml`
    convertCollection();
    res.json({ message: "Successfully uploaded files" });
}

app.post("/upload_files", upload.array("files"), uploadFiles);

请大家帮帮我。

【问题讨论】:

    标签: javascript node.js express frontend


    【解决方案1】:

    您已经在使用res.send,它将响应标头发送回客户端,结束请求响应周期,当您尝试执行res.download 时,它会引发错误。改为使用

     app.get('/download', (req, res) => {
          const file = './downloads/output.yml';
            res.download(file, 'openapi.yml', (err) => {
                if (err) {
                    console.log(err)
                } else {
                    console.log('file downloaded')
                }
            });
        });
    

    res.send('file downloaded')--->删除这一行

    你也需要更新你的js代码

    const handleDownload = async () => {
        const res = await fetch("https://cors-anywhere.herokuapp.com/download"); //http://localhost:5000--->this is not required
        const blob = await res.blob();
        download(blob, 'output.yml');
    }
    
    downloadBtn.addEventListener('click', handleDownload);
    

    【讨论】:

    • 您好,感谢您的帮助 现在,当我点击localhost:5000/download 这个时,我可以下载文件了。但是当我点击前端的下载按钮时,它仍然显示相同的错误消息并下载一个空文件 script.js:24 GET cors-anywhere.herokuapp.com/http://localhost:5000/download 403 (Forbidden)
    • 现在,它在前端显示此错误消息“加载资源失败:服务器响应状态为 403(禁止)”,后端显示此错误消息“node:19280)UnhandledPromiseRejectionWarning:类型错误:无法读取未定义的属性“路径”
    • 我在您的问题中看不到path,请更新问题
    • 这是上传过程的一部分,你应该看到这个 -stackoverflow.com/questions/35851660/…
    • 不知道为什么调用上传路由
    猜你喜欢
    • 2019-08-05
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 2020-03-15
    • 1970-01-01
    相关资源
    最近更新 更多