The router should not contain the functions.
Router should just be a list of routes.
Controller should have the functions.
In the root create dir controllers.
Create 3 new files in this
userController.js postController.js followController.js
Example of how we will user a controller
in router.js
router.post('create-post', postController.create)
Right now we have something like this
router.get('/', function(req, res){
res.render('home-guest')
})
The function gets replaced with a controller file and the function is inside that controller file
Similar example for login
router.post('login', userController.login)
These two routers were examples. Delete them.
Delete the /contact route also if you have it.
In userController.js
We want to export multiple functions
exports.login = function() {
}
Node will know what to do with this. When this userController.js is required in any other file it will export all these functions.
Have a logout also and register.
Another one home.
- login
- logout
- register
- home
Start with home
exports.home = function(req, res) {
res.render('home-guest')
}
Require this file on the top
const userController = require('./controllers/userController')
Now change the router.get function
Get rid of the anonymous function
router.get('/', userController.home)
Check to see if your app is still working fine.
Router and controller done.
Register form.
See where the form points.
Line 42.
Make action "/register"
In router.js
router.post('/register', userController.register)
Go to userController.js
exports.register = function(req, res) {
res.send("Thanks for trying to register")
}
Try to submit form
Should be working
We need to do server side validation for this
This logic will go in the model
MVC overview
Model - business logic (validation) View - presentation (HTML) Controller - this sees if the request should go to model or view. Middleman.