Javascript 如何在不使用pug的情况下直接将变量从nodejs传递到html?

Javascript 如何在不使用pug的情况下直接将变量从nodejs传递到html?,javascript,node.js,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.v

我需要将变量从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>
3.9

我已经在我的配置中设置了这个版本号,我已经在login.js中导入了这个版本号,但是仍然没有得到输出。有人知道吗?

如果您不想使用ejs或pug之类的模板引擎,那么您可以使用axios或
fetch
向节点服务器发送get请求并发送响应

这里有一个关于如何做到这一点的示例。根据你的需要改变它

index.html

<!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>

如果变量为空,请尝试
console.log()?在你的程序中使用ejs或类似的东西来呈现你的页面,如果你愿意,我可以添加一个例子,如果你愿意,就试试吧can@jank我也尝试过这种方法var name=“”;console.log(名称);但我不是getting@GaneshKarewad请添加一个示例Well one thing worked loginRouter.get('/',(req,res)=>{res.render(path.dirname(uuu dirname)+'/views/login.html',{version\u no:config.version\u number});HTML每个人都缺少结束百分位数,没有其他的开始-结束百分位数可以让你的代码工作。对不起,我找不到你。您现在是否正在html中获取变量值?如果你正在从节点JS文件中通过,如果你的问题被解决了,那就给你变量,如果有帮助的话,考虑一下投票和接受答案,或者让我知道如果你有任何其他错误。
const express = require('express');

const app = express();

const PORT = 5000;

app.get('/', (req, res) => {
    res.sendFile('index.html', {root: __dirname });
});

app.get('/version', (req, res) => {
    const myVersion = 'My version is 0.5';
    res.json(myVersion);
});

app.listen(PORT, () => {
    console.log(`Server running on PORT ${PORT}`);
});