4

I am using client side to send a post request to node js server to perform a long request. During the process, I want the server side can let the client side know how much work is already done and which step it is currently in. So I am wondering if there is a way for the server side to constantly sending events where the client side can receive. Something that can be received by $(document).on(). But It doesn't have to be limited in this way though.

It seems to be $.post only takes data from server side once. So how can I be able to continuously receive server side data after posting?

0

3 Answers 3

5

Since you only want to send messages from the server to the client, you can also use Server-Sent Events (SSE).

You can setup listeners for the SSEs in your client-side script like this:

var serverEvents = new EventSource('http://localhost:8080/events'); serverEvents.addEventListener('message', function(event){ console.log(event.data); }); 

The browser will send a request to the URL provided when creating the new EventSource to establish a connection, then, from the server, you only need to send the messages in a particular format, for instance:

data: some data data: {"name": "bobby"} 

The individual messages must be separated by a pair of newline characters.

Node.js example:

const http = require('http'); const server = http.createServer((req, res) => { if( req.url === '/events'){ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Access-Control-Allow-Origin': '*' }); setTimeout(() => { res.write('data: some data\n\n'); }, 1000); } }); server.listen(8080, '127.0.0.1'); 

Check out this link for more information: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

Sign up to request clarification or add additional context in comments.

Comments

2

You need to use socket.io to do that.

See this example https://github.com/socketio/socket.io

Comments

2

The only way for creating a real-time communication between server and client side is using websockets. As already mentioned by @Nonemoticoner, the most famous websocket library is Socket.io

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.