简体   繁体   中英

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

And the request gets sent and I get this error in the terminal:

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

At http server, we can send response once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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