简体   繁体   中英

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. 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:

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 . That's the path where static HTML, images, scripts and other files are hosted. 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 "

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. 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.

If you have /views/index.pug that contains something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM