Full-Stack Web Development with Vue.js and Node

(singke) #1
Building an Express Application Chapter 2

// Include controllers
fs.readdirSync('controllers').forEach(function (file) {
if(file.substr(-3) == '.js') {
const route = require('./controllers/' + file)
route.controller(app)
}
})

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

Let's move ahead with adding a route to our controller. Let's create a folder in the root of
the application called controllers and add an index.js file to the controllers folder


and paste the following code:


module.exports.controller = (app) => {
// get homepage
app.get('/', (req, res) => {
res.render('index', { title: 'Express' });
})
}

Now, all of our routes will be handled by the controller files, which means we don't need
the codes in app.js that control the routing. Hence, we can remove these lines from the


file:


var index = require('./routes/index');
var users = require('./routes/users');

app.use('/', index);
app.use('/users', users);

Actually, we don't need that routes folder any longer. Let's also remove the routes


folder.


Similarly, let's add a new route that controls all the user-related operations. For that, add a


new file to the controllers folder called users.js and paste the following code inside it:


module.exports.controller = (app) => {
// get users page
app.get('/users', (req, res) => {
res.render('index', { title: 'Users' });
})
}
Free download pdf