Back to Courses

World's Best MERN Stack Course

MERN Tutorial #5: Controllers in Express.js πŸ”₯ Managing Your Application's Logic

Welcome, In this video, we're going to explore what controllers are in Express.js in this video, find out why they matter, how to structure folders, and how to handle requests. It'll show you how to create your "Home" controller and how to integrate it seamlessly with your router file. You'll also learn how to simplify controller function names using objects in your routes. Become an Express.js expert by mastering controllers!

auth-controller.js

// *----------------------
//* Controllers
// *----------------------

//? In an Express.js application, a "controller" refers to a part of your code that is responsible for handling the application's logic. Controllers are typically used to process incoming requests, interact with models (data sources), and send responses back to clients. They help organize your application by separating concerns and following the MVC (Model-View-Controller) design pattern.

// *-------------------
// Home Logic
// *-------------------
const home = async (req, res) => {
  try {
    res.status(200).json({ msg: "Welcome to our home page" });
  } catch (error) {
    console.log(error);
  }
};

// *-------------------
// Registration Logic
// *-------------------
const register = async (req, res) => {
  try {
    res.status(200).send({ message: "registration page" });
  } catch (error) {
    res.status(500).json({ message: "Internal server error" });
  }
};

module.exports = { home, register };

auth-route.js

const express = require("express");
const router = express.Router();
const authControllers = require("../controllers/auth-controller");

router.route("/").get(authControllers.home);
router.route("/register").get(authControllers.register);

module.exports = router;

server.js file

const express = require("express");
const app = express();
const router = require("./routes/auth-route");

// Mount the Router: To use the router in your main Express app, you can "mount" it at a specific URL prefix
app.use("/api/auth", router);

const PORT = 5000;
app.listen(PORT, () => {
  console.log(`server is running at port: ${PORT}`);
});