Home > other >  How to pass data from nodejs to inside html script tags
How to pass data from nodejs to inside html script tags

Time:02-07

I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags. name variable is coming as a empty string now. How can i console.log name variable's value?

static-pages-server.js:

 app.get('/index', function(req, res) {
        var name = "hello"; 
        res.render(__dirname   "/static-pages/journey-analize-report/index.html", {name:name});
    });

index.html:

 <script type="text/javascript">
        console.log(name);
 </script>

Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.

<script type="text/javascript">
        console.log(<%=name%>);
 </script>

CodePudding user response:

Express.js itself is a backend server. If you would like to have dynamic HTML files you need to use templates engines.

Please follow this document -> https://expressjs.com/en/guide/using-template-engines.html

Eventually, you will realize you will need a frontend framework to write your code faster with good quality. So also recommend you to take a look at some of the frameworks like React, Vue.js. If you need Single Page Applications you only use express.js to provide not for HTML renders. If you need Server-side rendering it is good to investigate Next.js, Nuxt.js.

CodePudding user response:

You cant directly inject variables into a html file in nodejs . That is why you have templating engines in express. Check out ejs.

It would allow you to pass data directly from your routes into the page you are rendering.

CodePudding user response:

Local variables sent to a view via the locals parameter using the res.render() method aren't directly accessible. Instead you need to refer to those using it's variable name wrapped inside double curly brackets. So if you want to use it inside a JavaScript function, you need declare a local variable and give it the content of your name local.

Simply modify your index.html like this:

<script type="text/javascript">
    let name = "{{name}}";
    console.log(name);
</script>

CodePudding user response:

here is the answer How do I use HTML as the view engine in Express?

what you will need is a view engine package in your app. there are many view engines currently available.

then set that view engine in express app. Trigger the view render via a call from your route’s response like you have done above.
Then in your view render the html output using the view variables and if these variables are outputted into html you can use them in your in browser JavaScript. You can also call a service in your html sending the dynamic data as well.

check out esj or pug (ps pug is my personal favourite )

  •  Tags:  
  • Related