JeduMiSePalacinke
JeduMiSePalacinke

Reputation: 77

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)

Upvotes: 0

Views: 62

Answers (1)

Wang Liang
Wang Liang

Reputation: 4444

//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.

Upvotes: 1

Related Questions