【问题标题】:ExpressJS: call a variable from .js file to index.htmlExpressJS:从 .js 文件调用一个变量到 index.html
【发布时间】:2018-07-13 04:57:18
【问题描述】:

我正在使用 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 方法吗?我在两者之间缺少什么?任何帮助/提示/指导将不胜感激!

谢谢

【问题讨论】:

标签: javascript html express variables get


【解决方案1】:

您必须 use a template engine 让您将视图文件中的变量替换为实际值,并将模板转换为发送给客户端的 HTML 文件。

与express结合使用的视图引擎有很多,你可以在这里选择一个:https://expressjs.com/en/guide/using-template-engines.html

我建议你使用ejs,因为它很容易理解,下面是一个使用它的例子:

ma​​in.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>

【讨论】:

    【解决方案2】:

    您正在使用 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>);
    

    【讨论】:

    • 这让我想到了我一直缺少的视图引擎。但是,我从运行中得到的输出是:{{ name }}
    • 只要你得到的输出 {{ name }} 这仅仅意味着没有任何东西(即视图引擎)实际上正在接受它来替换它。你有没有 npm install hbs (或任何其他视图引擎,我只是个人只熟悉 hbs 但还有很多其他的)?您是否正确启动了它?您的文件结构是否符合 hbs 要求,您是否配置了正确的设置?您是否使用正确的语法和详细信息发送 app.get?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    相关资源
    最近更新 更多