繁体   English   中英

ExpressJS:将.js文件中的变量调用为index.html

[英]ExpressJS: call a variable from .js file to index.html

我正在使用express@4.16.2

我想从main.jsindex.html调用一个变量

main.js:

const express = require('express')
const app = express()
var router = express.Router()
app.use('/',express.static('public'));

app.get('/main', function(req, res) {
    res.send("index", {name:'hello'});
});

app.listen(3000, () => console.log('listening on 3000'));

index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
  <link rel="icon" href="images/favicon.png">
</head>

<body>
  <<h1>{{ name }}</h1>
</body>
</html>

这将在网页上产生以下结果:

{{ name }}

我需要进行http get方法调用吗? 我之间缺少什么? 任何帮助/提示/指导将不胜感激!

谢谢

您必须使用模板引擎 ,该引擎可以用实际值替换视图文件中的变量,并将模板转换为发送给客户端的HTML文件。

与Express结合使用的视图引擎很多,您可以在这里选择其中之一: https : //expressjs.com/en/guide/using-template-engines.html

我建议您使用ejs,因为它很容易理解,这是一个使用它的示例:

main.js

const express = require('express')
const app = express()
var router = express.Router()
app.use('/',express.static('public'));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.get('/main', function(req, res) {
    res.send("index", {name:'hello'});
});

app.listen(3000, () => console.log('listening on 3000'));

index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link rel="icon" href="images/favicon.png">
</head>

<body>
<!-- show name -->
<<h1><%= name %></h1>
</body>
</html>

您正在使用hbs语法:

<<h1>{{ name }}</h1>

无需加载hbs视图引擎来渲染它。

hbs的示例:

const express = require('express');
const hbs = require('hbs');

const app = express();

app.set('view engine', 'hbs');

app.get("/main", (req, res) => {
    res.render("index.hbs", {
        name: "hello"
    });
});

app.listen(<port>);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM