[英]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
的方法,盡管沒有用:
<h1>{{ text }} </h1>
<h1><% text %> </h1>
<script type="text/javascript">
var text = "<%= text %>";
var text2 = "{{ text }}";
</script>
有什么想法我要去哪里錯嗎?
選項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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.