App.set ('views', __dirname + '/ views') in Express & node.js
I am confused about the app.set () method. As far as I know, app.set () looks like this:
app.get('title');
// => undefined
app.set('title', 'My Site');
app.get('title');
// => "My Site"
but in tutorials create a "views" folder and use that.
app.set('views', __dirname + '/views')
app.get('/') or app.get('/admin')
Shouldn't it be like this?
app.get(views)
app.set(name, value)
Assigns a parameter name to a value, where name is one of the properties from the application settings table .
view
Type: String or Array
A directory or array of directories for application views. If an array, the views are scanned in the order in which they appear in the array.
app.set('views', path.join(__dirname, 'views'));
This will set your apps view folder to something like:
/ Users / Adil / Project / MYAPP / views
When you actually go to use the view, the name view
becomes the file path, minus the root directory
and the file extension. For example, if you had the following file structure:
/views/
/views/index.hbs
/views/news/
/views/news/index.hbs
/views/news/article1.hbs
/views/news/article2.hbs
You should render the views like this:
res.render('index', {});
res.render('news/index', {});
res.render('news/article1', {});
res.render('news/article2', {});
views
is a config variable that sets the folder from which express will grab templates. app.get('/admin')
is also different from app.get('variable')
. First is the GET route that the HTTP server will listen to, the second is just the expression environment variable.
- Methods
app.get()
andapp.set()
in express.js - it's not something that we use to use OOP. When we useapp.get('key')
orapp.set('key', 'value')
in OOP like java, we just want to set / get the member of the object. - In express.js, however, it is
app.set()
used to set one of the application settings. see http://expressjs.com/en/4x/api.html#app.set . The methods used hereapp.get()
andapp.post()
refer to the routes and request received by the node.js server. eg:app.get()
refers to requestGET
andapp.post()
refers toPOST
request