繁体   English   中英

在 Express.js 中下载文件

[英]Downloading a file in Express.js

server.js

app.post('/api/download', async (req, res) => {
    res.json({status: 'ok'})
    return res.download('pera.txt', 'pera.txt')
})

index.js

async function download()
{
    const result = await fetch('/api/download', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body:
        JSON.stringify({
            token,
        })
    }).then((res) => res.json())
}

请求被发送,我在终端中收到此错误:

Error: Can't set headers after they are sent.
    at SendStream.headersAlreadySent (/home/pera/Desktop/P2/node_modules/send/index.js:390:13)
    at SendStream.send (/home/pera/Desktop/P2/node_modules/send/index.js:617:10)
    at onstat (/home/pera/Desktop/P2/node_modules/send/index.js:729:10)
    at FSReqWrap.oncomplete (fs.js:154:5)
//res.json({status: 'ok'}) // remove this


//res.download(path [, filename] [, options] [, fn])


return res.download('pera.txt', function (err) {
    console.log(err)
})

在 http 服务器上,我们可以发送一次响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM