Norman Bird Norman Bird - 1 year ago 98
jQuery Question

how to access session variables from express and nodes js in function.js

I am able to set and access session variables, like req.session.t1, etc. and all works fine on server side. On client side I have jquery installed on the front end and accessed by jade template.

I have in functions.js:


var t1 = req.session.t1;



So as page/jade template loads, jquery does append the the data as outlined IF I use constants or a string, but session variables are undefined if I use req.session.x or session.x.

So question is, how would I best be able to manipulate via jQuery, session variables? Or do I need to save to DB and pull it up each time? I'm newbie and not sure how to do this in node js and express and jquery.

Ven Ven
Answer Source

Node.js/express run on the server.

jQuery runs on the client.

The only thing that's shared is whatever you've sent to the client.

If you want a variable to be accessible client-side, you need to send it in the response.

If you're giving the server JSON back, just add a field.

res.send({t1: req.session.t1}); // (node.js side)

If you're outputting a template, you can write it in a HTML tag, or directly in a script tag.

Jade example:

script. // .jade file
  var t1 = "#{t1}"

And in the server:

res.render('template.jade', {t1: req.session.t1});