I want to create a server, when a GET is requested for which the date and time will be displayed in the server console. And after a certain interval, complete the server response and return the time to the client.

I do it this way.

const http = require('http'); const port = 3000; const getDateToUTC = () => (new Date).toUTCString(); const server = http.createServer((req, res) => { if (req.method === 'GET') { const interval = setInterval(() => console.log(getDateToUTC()), 1000); setTimeout(() => { clearInterval(interval); res.end(getDateToUTC()); }, 5000) } }); server.listen(port, () => { console.log(`Server running on port: ${port}`); }); 

But! When a server is repeatedly accessed, the function will only work when all previous answers have been given.

Those. I open two tabs in the browser and switch to localhost:3000 . I try to quickly go, well, probably, there will be a difference of 500 ms between requests. And I expect to receive answers from the server at the same interval.

In fact, the second request begins to be processed only after the first one is completed, i.e. after 5 seconds in this example.

enter image description here

How to make requests work asynchronously?

  • "In fact, the second request begins to be processed only after the first is completed, i.e. after 5 seconds in this example," No. Why do you think so? - Suvitruf ♦
  • I attached a screen. - Igor
  • And what's on the screen? You simultaneously opened two tabs, but did the processing of the second just in 5 seconds begin? What is the version of nodejs? And then I have no such problem at 8. - Suvitruf ♦
  • Yes it is! last v10.9.0 - Igor
  • The problem is in Chrome itself (: I made the answer. - Suvitruf ♦

1 answer 1

It is interesting. Everything works fine in Firefox. And in Chrome, the request is not sent on the second tab until you receive a response to the first request.

Judging by the logs, this is not a node.js problem, but a browser.

At en SO, this was discussed :

Yes, this is a request for the same resource again. The answer is unique. I added a random number to the query string, and everything is working now.

Chrome locks cache and waits for a response to the first request. To get around this, you need to make the request unique. For example, you can open not http: // localhost: 3000 two times, but http: // localhost: 3000 /? Id = 2 and http: // localhost: 3000 /? Id = 1

If you plan to send these requests from the console / programmatically, then you can add Cache-Control: no-cache, no-transform request headers Cache-Control: no-cache, no-transform , this should also help.

  • Thank you very much!! You're right! - Igor
  • @Igor glad to help) - Suvitruf ♦