ExpressJS:将参数传递给html不起作用

时间:2017-10-13 03:29:36

标签: javascript html node.js express

以下是我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"});
});

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

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

我想出错的任何想法?

1 个答案:

答案 0 :(得分: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');