Wednesday, 19 April 2017

Nodejs express can't set headers after they are sent (quick page refresh)

I know that similar questions have been asked but I still can't understand what my this problem is.

What I am doing is the following:

1) Receive an http request

2) Perform n SSH (using the ssh2 module) connections to n different servers as callbacks which (to my understanding) will run on n separate threads.

3) Perform actions on these servers which might take up to 10 s

4) When all SSH connections have been attempted (failure or success) render server.html page using res.render to send it back to the user.

5) So the processing time each http request is around 10 s

My problem is the following:

1) Using a browser, if I visit server.html and then refresh the same page quickly I am getting the "can't set headers after they are send" error .

2) When using different tabs, and refresh server.html on both tabs, the requests seems to be handled correctly (added to the event queue) and processed one after the other.

For case 1) I am not sure why the second request is not added to the event queue and processed after the first one has finished. How come the second request is processed before the first one is returning? It seems that once the first request hits the SSH function (which run on sepearte threads and stack is empty at that point) the second request starts processing and finish at around the same time as the first request and therefore the headers are being sent twice on the same res object. Is this the expected behavior (maybe because the two requests req objects are somehow similar)? If it is, what is the best way to prevent? If not, do you have any suggestions of what might be going wrong? Please let me know if you need additional info.



via M.Q

No comments:

Post a Comment