node.js - Pass variables to JavaScript in ExpressJS -
i lost on this; using nodejs fetch json , need pass variable page , have javascript use data.
app.get('/test', function(req, res) { res.render('testpage', { myvar: 'my data' }); that express code (very simple testing purposes); using ejs want gather data know render on page simply
<%= myvar %> but need able gather data in javascript (if possible within .js file) display variable in alert box have tried
in jade alert('!{myvar}') or !{json.stringify(myvar)}. can similar in ejs. don't need field <input type=hidden> , taking value of field in javascript. if can appreciated
you use (client-side):
<script> var myvar = <%- json.stringify(myvar) %>; </script> you ejs render .js file:
app.get('/test.js', function(req, res) { res.set('content-type', 'application/javascript'); res.render('testpage', { myvar : ... }); }); however, template file (testpage) still need have .html extension, otherwise ejs won't find (unless tell express otherwise).
as @ksloan points out in comments: have careful myvar contains. if contains user-generated content, may leave site open script injection attacks.
a possible solution prevent happening:
<script> function htmldecode(input){ var e = document.createelement('div'); e.innerhtml = input; return e.childnodes.length === 0 ? "" : e.childnodes[0].nodevalue; } var myvar = json.parse(htmldecode("<%= json.stringify(myvar) %>")); </script>
Comments
Post a Comment