3

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.

3 Answers 3

2

You should look into using a template language for your HTML. There are several available, just search for node.js template language or using npm:

npm search templates

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

Sign up to request clarification or add additional context in comments.

1 Comment

{{ Mustache }} Templating is the easiest and most intuitive to learn for a beginner IMO
1

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 (<body data-token="...">) 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.

4 Comments

How would I append the data attribute to the body tag? On the client I would use jquery but I'm not sure how I would do this from server-side.
You need to use some kind of template engine; right now you only read a static file without any proper way to substitute values inside it.
OK. I was trying to hold off on learning a template engine until I become better versed in node by itself. Perhaps this is just one of those use-cases where a template engine is absolutely required.
You have a plain string so you can always .replace('{TOKEN}', token) and then put {TOKEN} in your HTML file. For a single value that's actually fine, but if you need more, better use a template engine.
0

Put something like:

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

in your HTML, then replace the {{TOKEN}} string with the token at 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's variables to the client. It's probably not what you want for passing a simple token, but it might be of interest.

1 Comment

Thanks. Your answer works as well. +1 for the nowjs tip. I'll check it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.