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"});
response.end(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
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.
source to share
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 (http://nowjs.com/) 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.
source to share