如何不使用pug将变量直接从nodejs传递到html?

时间:2019-06-04 06:53:02

标签: javascript node.js

我需要将变量从NodeJS文件传递到呈现的html文件。该怎么做?

以下是我尝试过的内容

Nodejs代码

const loginRouter= express.Router();

const config= require('../config/config.json');

loginRouter.get('/', (req,res)=>{

    res.render(path.dirname(__dirname)+'/views/login.html',{version:config.version});

    //res.json('done')
});

HTML代码

<label style="font-size:10px;float: right;"><%= version %></label>

当前结果:- 什么都没来

预期结果:-

<label style="font-size:10px;float: right;">3.9</label>

我已经在我的login.js中导入的配置中设置了此版本号,但是仍然没有得到输出。有人对此有任何想法吗?

1 个答案:

答案 0 :(得分:0)

如果您不想使用 ejs pug 之类的模板引擎,则只需使用axios或{{1 }}到您的节点服务器并发送响应。

以下是有关如何执行此操作的示例。根据需要进行更改。

index.html

fetch

server.js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1 id="title">My page</h1>
    <script>
        fetch('http://localhost:5000/version').then(function(response) {
            return response.json();
        }).then(function(myJson) {
            document.getElementById('title').innerHTML = myJson;
        });
    </script>
</body>
</html>