ExpressJS:将参数传递给html不起作用(ExpressJS: passing parameters to html doesn't work)

编程入门 行业动态 更新时间:2024-10-24 10:20:06
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');

更多推荐

本文发布于:2023-04-28 00:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329082.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   参数   html   ExpressJS   parameters

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!