Controllers

A GET request route that is set up in a separate route File instead of the server.js file.

/** greetingRoute.js */ 
...
router.get('/', (req,res) => {
   res.status(200).json({ message: "Greetings!"});
});
...

We could set up routes like this, they aren't doing much currently but they are set up. We could proceed to add our functionality in the body of these callback functions but it's much better to practice creating a controller and have your functions there.

So, in the backend folder that we had, create a controllers folder and add a file for the corresponding controller. Lets say, greetingController.js

Here, we can create some functions. For instance, let's have a getGreeting function

/** greetingController.js */

const getGreeting = (req,res) => {
    res.status(200).json({ message: "Greetings!"});
}

module.exports = {
    getGreeting,
}

We need to export it to use it in our routes file.
The modules.exports is an Object here because we might wanna add more functions to it later as routes grow.

So, now in our routes file, we need to require it.

/** greetingRoute.js */
...
const { getGreeting } = require('../controllers/greetingController.js');
...

router.get('/', getGreeting);

...

Notice how we replaced the callback function body with the getGreeting function that we pulled in via require above.
And it should still work!

You wanna do these with the rest of the routes as well and clear the clutter from the routes file as well.

And when you are done with all the routes, you can chain the same routes but different request types together, like so

...

router.route('/').get(getGreeting).post(setGreeting);
router.route('/:id').update(updateEntity).delete(deleteEntity);

...
module.exports = router;

That's it for this one. Leave a like!