Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access server variable in client side (node.js + express)

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?

like image 510
agp Avatar asked Oct 31 '25 01:10

agp


2 Answers

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

like image 99
teaflavored Avatar answered Nov 02 '25 13:11

teaflavored


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.

like image 26
Bernardo Loureiro Avatar answered Nov 02 '25 14:11

Bernardo Loureiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!