DEV Community

Viraj Nirbhavane
Viraj Nirbhavane

Posted on

Controllers

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

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

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 practice to create 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, lets have a getGreeting function

/** greetingController.js */

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

module.exports = {
    getGreeting,
}
Enter fullscreen mode Exit fullscreen mode

We need to export it in order to use it in our routes file.
The modules.exports is a 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);

...
Enter fullscreen mode Exit fullscreen mode

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 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 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;
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)