Passing a variable from node.js to html

2020-01-25 09:56发布

I am trying to pass a variable from node.js to my HTML file.

app.get('/main', function(req, res) {
  var name = 'hello';
  res.render(__dirname + "/views/layouts/main.html", {name:name});
});

9条回答
淡お忘
2楼-- · 2020-01-25 10:30

Other than those on the top, you can use JavaScript to fetch the details from the server. html file

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
      <div id="test">
      </div>
    <script type="text/javascript">
        let url="http://localhost:8001/test";
        fetch(url).then(response => response.json())
        .then( (result) => {
            console.log('success:', result)
            let div=document.getElementById('test');
            div.innerHTML=`title: ${result.title}<br/>message: ${result.message}`;
        })
        .catch(error => console.log('error:', error));
    </script>
  </body>
</html>

server.js

app.get('/test',(req,res)=>{
    //res.sendFile(__dirname +"/views/test.html",);
    res.json({title:"api",message:"root"});
})

app.get('/render',(req,res)=>{
    res.sendFile(__dirname +"/views/test.html");
})

The best answer i found on the stack-overflow on the said subject, it's not my answer. Found it somewhere for nearly same question...source source of answer

查看更多
家丑人穷心不美
3楼-- · 2020-01-25 10:31

I found the possible way to write.

Server Side -

app.get('/main', function(req, res) {

  var name = 'hello';

  res.render(__dirname + "/views/layouts/main.html", {name:name});

});

Client side (main.html) -

<h1><%= name %></h1>
查看更多
forever°为你锁心
4楼-- · 2020-01-25 10:33

What you can utilize is some sort of templating engine like pug (formerly jade). To enable it you should do the following:

  1. npm install --save pug - to add it to the project and package.json file
  2. app.set('view engine', 'pug'); - register it as a view engine in express
  3. create a ./views folder and add a simple .pug file like so:

html head title= title body h1= message note that the spacing is very important!

  1. create a route that returns the processed html:

app.get('/', function (req, res) { res.render('index', { title: 'Hey', message: 'Hello there!'}); });

This will render an index.html page with the variables passed in node.js changed to the values you have provided. This has been taken directly from the expressjs templating engine page: http://expressjs.com/en/guide/using-template-engines.html

For more info on pug you can also check: https://github.com/pugjs/pug

查看更多
登录 后发表回答