How to send some context from node server to html template without using any template engines

半腔热情 提交于 2020-01-14 04:10:09

问题


server.js

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

index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    title{{title}}
    message{{message}}
  </body>
</html>

how can i send title and message to index.html which is assigned in contex variable.

i found a lot of way to do it using some template engines like jade,ejs,pug etc.. but i want it in pure html.

please have a look into my code....


回答1:


Without using template engines like jade,ejs, pug or client side libraries like angular, react.
You cannot interpolate the meaning of {{title}} in the html side.

Another approach is using javascript to fetch the details from 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");
})


来源:https://stackoverflow.com/questions/53141364/how-to-send-some-context-from-node-server-to-html-template-without-using-any-tem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!