0

My Node Js server is exposing an API to build and download an APK file.
Expected behaviour:-
When the user open the API url in browser, I want to show him/her APK file building progress/status. On complete, Download the APK file.
Error:- I cannot call res.download(fileURL) after calling res.write('APK building Progress')
My code:-

function createPersonalAPKAndDownload(req, res) {

const email = req.query.email || req.body.email
if (!email) return res.send('Please enter your email address.')

res.setHeader('Content-Type', 'text/html')
res.write('Encrypting email and password ...<br>')

// Some work

res.write('Work progress or error')

// Some work 2

res.write('Work 2 progress or error')

// finally download the generated APK or write error

if (some_error) {
    res.write('some_error')
    return res.end()
}

res.download('path/to/apk/file') 
}

This code will throw error at res.download -> Error: Can't set headers after they are sent. at SendStream.headersAlreadySent

How can I make it work?

  • Does this answer your question? [Error: Can't set headers after they are sent to the client](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) – Jason May 22 '20 at 23:27
  • @Jason I know why it's happening. I just want to know different solution to my problem. – Abhinav Suthar May 23 '20 at 12:46
  • As far as I know, you don't know how this works. Just because you put the contents like "Work progress on error" into the stream, set the headers and you continue to tell them to download the file, that is not suppose to work like that. Either you remove all the res.setHeader and res.write methods, it will going to work as expected. Or you want to keep this approach, try RESTful API. – Jason May 25 '20 at 22:19

0 Answers0