Trigger res.redirect After res.download

1,304 views
Skip to first unread message

Wajdi Awwad

unread,
Mar 12, 2015, 11:15:46 AM3/12/15
to nod...@googlegroups.com
Hi, 

I have application with download pdf file buttons.
In my application, i need the app to redirect to another api after download finish.

I'm doing the following: 

   res.download('myPdfFile', function(err) {
if (err) {
console.log(err);
}

                                                       res.redirect('list/api');
});

But this return error {Can't set headers after they are sent.}

How i can trigger res.download and res. redirect once ? 

Thanks.

Petar Aleksic

unread,
Mar 12, 2015, 12:48:24 PM3/12/15
to nod...@googlegroups.com
I guess you are sending the body with res.download, and then trying to redirect users. For a redirection the headers / statusCode have to be sent as well, which causes the error in your case.

Ryan Schmidt

unread,
Mar 13, 2015, 9:53:26 AM3/13/15
to nod...@googlegroups.com
You can't do that. This is not a limitation of node; it's just not how HTTP works.

In response to an HTTP request, your HTTP server shall send exactly one HTTP response. That response will have headers. It may also have a body, depending on what headers you send.

For example, you could send headers that describe a file, and the body of the response would be the contents of the file.

Or, you could send headers including a Location header requesting that the user agent visit another URL. In that case, your response will have no body (or perhaps a simple HTML body with a link to the same URL, for the benefit of someone examining your site with curl).

Some web sites use the following strategy: when you click a download link, they actually send you to an HTML page. That page says something like "Thanks for downloading", or provides further information about the file, or displays advertisements or something. And the page uses HTML meta tags, or perhaps JavaScript, to request the actual file's URL, which is then downloaded while the user looks at the "thank you" page. Perhaps that strategy is helpful to you?

What exactly are you trying to do? What is this other API that you must hit after the download finishes?

If you really must wait until the download finishes, then only the server serving the file knows if it has been completely sent. You may have to write the server to have a route for serving the file, and when the server has finished serving the file, the server calls the other API. But this would not provide any opportunity for communicating any further result back to the user agent.

Reply all
Reply to author
Forward
0 new messages