Passing Variable from Node.js Server to Client

On my node.js server, I have the following code:

//Generate a token
var token = capability.generateToken();

//Serve the page
var html = fs.readFileSync('learn.htm').toString();
response.writeHead(200, {"Content-Type": "text/html"});


Now on the client side (in learn.htm) I want to access the token variable. My question is, how do I pass a variable to the client in the response? There should be an easy way to do this, but I'm struggling to get my head around me.


source to share

3 answers

You can send JavaScript to the client that sets the variable. Or you can store it in an attribute data-

for example. body ( <body data-token="...">

) tag and then access it via $('body').data('token')

if you have client side jQuery.

If you need it for a form, you can also save it in a hidden input field.



You should learn the templating language for your HTML. There are several available, just search for the node.js template language or use npm:

npm search templates


Edit: Some popular ones: jade , ejs , hogan.js .



Place something like:

<input type="hidden" value="{{TOKEN}}"> 


in your HTML, then replace the {{TOKEN}} string with a token on each request.

Then use JS like:

var token = $("input#csrf_token").val();


to get the value in your client script.

Edit: I haven't used it myself, but nowjs ( is a more general way of getting your server variables to the client. This is probably not what you want for a simple token transfer, but it might be interesting.



All Articles