【问题标题】:ExpressJS: passing parameters to html doesn't workExpressJS:将参数传递给 html 不起作用
【发布时间】:2017-10-13 03:29:36
【问题描述】:

这是我在server.js 中的内容:

var browserify = require('browserify-middleware');
var express = require('express');
var app = express();
var path    = require("path");

app.listen(8080);
console.log('Listening at http://localhost:8080');

// routes will go here
app.get('/render', function(req, res) {
    res.sendFile(path.join(__dirname+'/public/index.html'), {text: "sfsdfsf"});
});

这是我尝试在我的index.html 中获取变量text 的方法,但没有任何效果:

<h1>{{ text }} </h1>
<h1><% text %> </h1>
<script type="text/javascript">
var text = "<%= text %>";
var text2 = "{{ text }}";
</script>

有什么想法我哪里出错了吗?

【问题讨论】:

  • res.sendFile() 没有您尝试使用的任何模板功能。您需要使用实际的模板引擎(pug、车把、灰尘、ejs 等),然后使用res.render() 将数据传递给它以用于渲染。
  • 我给了你四个模板引擎,它们都有使用 Express 的文档。请自己做一些功课,然后如果遇到困难,可以提出更具体的问题。从哈巴狗开始。

标签: javascript html node.js express


【解决方案1】:

选项1:我建议添加像哈巴狗这样的模板引擎。模板引擎用实际值替换模板文件中的变量。要实现 pug 模板,请访问https://expressjs.com/en/guide/using-template-engines.html

选项 2:

'use strict';

var express = require('express');

var path = require("path");
var app = express();


const template = (text) => {
return `
 <!DOCTYPE html>
 <html>
   <head>
    <title>sample</title>
   </head>
   <body>
    <h1>${text}</h1>
   </body>
 </html>`;
}

app.get('/render', function(req, res) {
  res.send(template('Hello'));
});

app.listen(8080);
console.log('Listening at http://localhost:8080');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-28
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2021-03-15
    • 2015-09-09
    相关资源
    最近更新 更多