作为我在 NodeJS 上尝试的第一件事,我正在构建一个简单的应用程序,它显示一个 HTML 页面,告诉访问者他们的 IP 地址。
这是它的样子
var express = require('express');
var app = express();
app.set('view engine', 'mu2');
app.get('/', function (req, res) {
res.setHeader('Content-Type', 'text/html'); // Do I have to do this? I'm not sure.
res.render('frontPage.html', {
ip: req.ip
});
res.send();
});
app.listen(8080, function() {
console.log("Listening on port 8080");
});
这是/views/frontPage.html
的样子:
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<h1>Hello, World!</h1>
<hr>
<p>If you're reading this, the NodeJS setup is working. Check your developer console. See if there's any HTTP error in there.</p>
<p>Anyway, your IP address is {{ip}}</p>
</body>
</html>
这是我每次发送请求时在控制台中得到的内容:
TypeError: this.engine is not a function
at View.render (/Users/macuser/NodeJS/hello/node_modules/express/lib/view.js:126:8)
at tryRender (/Users/macuser/NodeJS/hello/node_modules/express/lib/application.js:639:10)
at EventEmitter.render (/Users/macuser/NodeJS/hello/node_modules/express/lib/application.js:591:3)
at ServerResponse.render (/Users/macuser/NodeJS/hello/node_modules/express/lib/response.js:960:7)
at /Users/macuser/NodeJS/hello/index.js:8:9
at Layer.handle [as handle_request] (/Users/macuser/NodeJS/hello/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/macuser/NodeJS/hello/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/Users/macuser/NodeJS/hello/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/macuser/NodeJS/hello/node_modules/express/lib/router/layer.js:95:5)
at /Users/macuser/NodeJS/hello/node_modules/express/lib/router/index.js:277:22
我已经在 views/
中设置了 frontPage.html
,并且已经从 NPM 安装了 Mustache (npm install mu2 --save
)。
这是怎么回事?
最佳答案
我最终绕过了 Express 的模板系统并使用 Mustache 自己的 compileAndRender()
。像这样:
var express = require('express');
var app = express();
var mu2 = require('mu2');
mu2.root = __dirname + '/views';
app.get('/', function (req, res) {
var htmlStream = mu2.compileAndRender('frontPage.html', {ip: req.ip});
htmlStream.pipe(res);
});
app.listen(8080, function () {
console.log("Listening on port 8080");
});
现在可以使用了。
关于node.js - 尝试在 Express JS 中使用 Mustache 时出现 TypeError : this. 引擎不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40934450/