【问题标题】:Send a variable to HTML with express sendfile (short question)使用 express sendfile 将变量发送到 HTML(简短问题)
【发布时间】:2020-06-08 17:49:57
【问题描述】:

我正在使用 Node.JS、路径和 express 来运行 HTML 网页,并且需要将变量发送到 HTML 以供其使用:

var client_cred_access_token = 'fakeToken';

...

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, '/public', 'homepage.html'));
});

如何将此字符串变量发送到 homepage.html?

【问题讨论】:

    标签: javascript html express path


    【解决方案1】:

    你需要一个模板引擎中间件,比如 pug / ejs 和 express 来实现这个功能。

    带有 ejs 库的示例代码。就npm i ejs

    const express = require('express');
    const app = new express;
    const path = require('path');
    
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');
    
    const client_cred_access_token = 'fakeToken';
    
    app.get('/', function (req, res) {
        res.render(path.join(__dirname, '/public', 'homepage.html'), {token: client_cred_access_token});
    });
    
    app.listen(3001);
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h1><%= token %></h1>
    </body>
    </html>

    参考:https://expressjs.com/en/resources/template-engines.html

    【讨论】:

    • 不幸的是,我无法使用 EJS,因为它与系统中的其他文件冲突。我以前看过这个答案,所以我很感激。
    • @RhettJarvis 列表中的其他模板引擎怎么样?
    猜你喜欢
    • 2016-12-09
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 2020-08-09
    • 2021-11-03
    相关资源
    最近更新 更多