Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

node.js - Pass variables to JavaScript in ExpressJS

I am completely lost on this; I am using NodeJS to fetch a JSON and I need to pass the variable to my page and have JavaScript use the data.

app.get('/test', function(req, res) {
    res.render('testPage', {
        myVar: 'My Data'
    });

That is my Express code (very simple for testing purposes); now using EJS I want to gather this data which I know to render on the page is simply

<%= myVar %>

But I need to be able to gather this data in JavaScript (if possible within a .js file) but for now just to display the variable in an Alert box I have tried

In Jade it is like alert('!{myVar}') or !{JSON.stringify(myVar)}. Can I do something similar in EJS. I don't need any field like <input type=hidden> and taking the value of the field in javascript. If anyone can help be much appreciated

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use this (client-side):

<script>
  var myVar = <%- JSON.stringify(myVar) %>;
</script>

You could also get EJS to render a .js file:

app.get('/test.js', function(req, res) {
  res.set('Content-Type', 'application/javascript');
  res.render('testPage', { myVar : ... });
});

However, the template file (testPage) would still need to have the .html extension, otherwise EJS won't find it (unless you tell Express otherwise).

As @ksloan points out in the comments: you do have to be careful what myVar contains. If it contains user-generated content, this may leave your site open for script injection attacks.

A possible solution to prevent this from 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...