[英]What is the difference between “views” path and the path used in express.static?
I have never used Express for more than a static HTML server serving JavaScript and HTML to WebSocket app. 我从来没有将Express用作用于向WebSocket应用程序提供JavaScript和HTML的静态HTML服务器。 I am now very confused with some example code which I'm trying to get to work. 现在,我对一些试图工作的示例代码感到非常困惑。
After I updated the example for latest Express version, the initialization code looks like this: 在将示例更新为最新的Express版本后,初始化代码如下所示:
var methodOverride = require('method-override');
var bodyParser = require('body-parser');
var errorHandler = require('errorhandler');
// One path...
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(methodOverride());
var path = require ('path');
// Another path
app.use(express.static(path.join(__dirname, '/public')));
I am familiar with the express.static
. 我对express.static
很熟悉。 That's the path where static HTML, images, scripts and other files are hosted. 这就是托管静态HTML,图像,脚本和其他文件的路径。 But the other path bothers me, I do not understand those two lines: 但是另一条路困扰着我,我不明白这两行:
app.set('views', __dirname + '/views');
app.set('view engine', 'pug'); // Maybe some HTML template parser???
The problem is, that this actually causes errors: 问题是,这实际上会导致错误:
Error: Failed to lookup view "index" in views directory "
... project path .../views
" 错误:无法在视图目录“... project path .../views
”中查找视图“索引”
I am not here just to fix the error though. 我不是在这里只是为了解决错误。 I'm far more interested in knowing what does the code I have mean. 我更想知道我的意思是什么代码。 Can anyone explain to me, what am I doing? 谁能告诉我,我在做什么?
views
are not static. views
不是静态的。 When you use the response.render
method, express
will look up the provided template name string to find a template which it then parses and emits. 当您使用response.render
方法时, express
将查找提供的模板名称字符串,以找到一个模板,然后解析并发出该模板。
If you have /views/index.pug
that contains something like: 如果您的/views/index.pug
包含以下内容:
html
body
h1= message
You can create a route: 您可以创建一条路线:
app.get('/' (req, res) => {
res.render('index', {message: "hello"});
});
If you want to access something in your static directory, you can use that route directly as well. 如果要访问静态目录中的内容,也可以直接使用该路由。
More information about express
template engine usage is here 有关express
模板引擎使用的更多信息,请点击此处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.