node.js - Firing server-sent events on page load in NodeJS (ExpressJS) -


i have code:

index.js:

var express = require('express'); var router = express.router();  router.get('/', function(req, res, next) {     res.writehead(200, {         'connection': 'keep-alive',          'content-type': 'text/event-stream',          'cache-control': 'no-cache'     });     res.write('event: proba\ndata: ' + json.stringify({ msg: "asdqqqq" }) + '\n\n'); }); 

and ejs file rendered (not index.js) script within app: testing.ejs:

<!doctype html> <html> <head> </head> <body> <script>     var source = new eventsource('/');       source.addeventlistener("proba", function(e) {         var jsondata = json.parse(e.data);         alert("my message: " + jsondata.msg);     }, false); </script> </html> 

my problem that, load ejs file in browser, message "asdqqqq" shows in alert, without loading "/" page. need that, event fires then, when load "/" page in browser. can me? thank you!


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -