4

I have a simple html page being served by express on a node.js server and in the client side javascript i want to access some server side variables. I tried googling around for a solution but didn't see a straight forward solution without using some sort of templating engine.

So if i need to access a variable on the server from a client side JS served from the same host, what do i need to do?

agp
  • 363
  • 5
  • 13
  • Output json to the document in a script tag, or make an AJAX request for the data. – elclanrs Mar 02 '16 at 21:34
  • Like @elclanrs said, output javascript between script tags in your document, use AJAX or - as a third option - use socket.io for realtime communication. – Sébastien Vercammen Mar 02 '16 at 21:35
  • Personally websockets are the way to go here. I hate having an express route setup to literally return a single variable. Being able to just send data over at anytime is just so much easier than all those xhr calls. – Sterling Archer Mar 02 '16 at 21:38
  • Using some sort of templating that access `res.locals`, either EJS, Jade or something you create yourself, is usually a good thing, and makes it easy to transfer data to the HTML at pageload without any additional requests. – adeneo Mar 02 '16 at 22:12

4 Answers4

2

To access the variable on the client, you'll need to expose it inside of a script tag, there are a few node modules that can help you with it (ex: express-state) https://www.npmjs.com/package/express-state, but you'll need a templating engine to generate the html required for it. You can use a variety of templating engines when working with express. If you use express generators straight out of the box it should come with jade and you can use different options on the generators to use other templating engines. See here for express generator options http://expressjs.com/en/starter/generator.html

teaflavored
  • 440
  • 4
  • 9
1

Create an API to expose your variable:

app.get('/myvar', function(req, res){
  res.send(varYouWantToSend);
 });

Then in the client-side make a call for that API with a http GET request. The url for the API would be www.yoursite.com/myvar in this example.

Community
  • 1
  • 1
0

You could try using this lib:

https://github.com/siriusastrebe/syc

and if you want to implement yourself look into Ajax. Jquery have a pretty simple ajax wrapper (http://api.jquery.com/jquery.ajax/). offcourse you need to open corresponding urls on the server to return / set the values.

Ronen Ness
  • 9,923
  • 4
  • 33
  • 50
0

Try socket.io http://socket.io/ it uses websockets on modern browsers and gracefully degradate to older technologies like AJAX with older browsers, leaving user experience the same.

Check out details here Web Socket support in Node.js/Socket.io for older browser

Community
  • 1
  • 1
Vlad Ankudinov
  • 1,936
  • 1
  • 14
  • 22