Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Passing Variable from Node.js Server to Client

Passing Variable from Node.js Server to Client

Problem

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 the variable to the client in the response? There must be a simple way of doing this but I'm struggling to wrap my head around it.

Problem courtesy of: hughesdan

Solution

You could send some JavaScript to the client which sets the variable. Or you could store it in a data- attribute e.g. of the body tag () and then access it via $('body').data('token') in case you have jQuery on the client side.

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

Solution courtesy of: ThiefMaster

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Passing Variable from Node.js Server to Client

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×