Skip to content

Instantly share code, notes, and snippets.

@tjkhara
Last active November 11, 2020 14:06
Show Gist options
  • Select an option

  • Save tjkhara/6afdbdbff731a3bbc733761607c54e1d to your computer and use it in GitHub Desktop.

Select an option

Save tjkhara/6afdbdbff731a3bbc733761607c54e1d to your computer and use it in GitHub Desktop.
Complex App Note 3 - What is a controller?

What is a controller?

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')
}

Go to router.js

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.

Second half

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment