ExpressJS:将参数传递给html不起作用(ExpressJS: passing parameters to html doesn't work)
这是我在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的方法,althgouh无效:
<h1>{{ text }} </h1> <h1><% text %> </h1> <script type="text/javascript"> var text = "<%= text %>"; var text2 = "{{ text }}"; </script>有什么想法我错了吗?
Here is what I have in my 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"}); });and here are the ways I tried to get the variable text in my index.html, althgouh none worked:
<h1>{{ text }} </h1> <h1><% text %> </h1> <script type="text/javascript"> var text = "<%= text %>"; var text2 = "{{ text }}"; </script>Any thoughts where I am going wrong?
最满意答案
选项1:我建议添加像帕格一样的模板引擎。 模板引擎用实际值替换模板文件中的变量。 要实施帕格模板,请访问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');Option1: I would suggest to add template engine like pug. Template engines replace the variables in a template file with actual values. To implement pug template, visit https://expressjs.com/en/guide/using-template-engines.html
Option 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');更多推荐
发布评论