![](/img/trans.png)
[英]Printing a HTML + JavaScript variable from an external js to an index.html file using fetch + node.js
[英]ExpressJS: call a variable from .js file to index.html
我正在使用express@4.16.2
我想從main.js
到index.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.