Controller in Express Js

  • In the context of Express.js, a controller is a module or set of functions that handle the application's business logic for specific routes. Controllers are responsible for processing requests, interacting with models or services, and sending an appropriate response back to the client. Organizing your code into controllers helps maintain a clean and modular codebase.
  • Let's go through the steps of creating and using controllers in an Express.js application.
Step 1: Project Structure
  • Create a project structure with folders for routes, controllers, and any other necessary modules.


    - my-express-app/
        - controllers/
            - userController.js
        - routes/
            - userRoutes.js
        - app.js
        - package.json

Step 2: Controller File (userController.js)

  • Create a controller file that exports functions to handle different aspects of the application logic.

    // controllers/userController.js

    const getUserById = (req, res) => {
        const userId = req.params.id;
        // Logic to fetch user from database using the userId
        const user = { id: userId, name: 'John Doe' };
        res.json(user);
    };

    const createUser = (req, res) => {
        // Logic to create a new user using data from the request body
        const newUser = req.body;
        // Save the user to the database
        // ...

        res.status(201).json(newUser);
    };

    module.exports = {
        getUserById,
        createUser,
    };


Step 3: Route File (userRoutes.js)

  • Create a route file where you define the routes and associate them with the corresponding controller functions.

    // routes/userRoutes.js

    const express = require('express');
    const router = express.Router();
    const userController = require('../controllers/userController');

    // Define routes and associate them with controller functions
    router.get('/:id', userController.getUserById);
    router.post('/', userController.createUser);

    module.exports = router;


Step 4: Main App File (app.js)

  • In your main app file, import the route file and use it to handle requests.

    // app.js

    const express = require('express');
    const userRoutes = require('./routes/userRoutes');

    const app = express();
    const port = 3000;

    // Parse JSON bodies
    app.use(express.json());

    // Use the userRoutes for paths starting with '/users'
    app.use('/users', userRoutes);

    app.listen(port, () => {
        console.log(`Server is running on http://localhost:${port}`);
    });


Step 5: Run the Application

  • Run your application using the command `node app.js` and test the routes.
    • To get a user by ID: `GET http://localhost:3000/users/123`
    • To create a new user: `POST http://localhost:3000/users`
Summary:
  • Controller (userController.js): Contains functions to handle specific aspects of the application logic, such as fetching users or creating new users.
  • Route (userRoutes.js): Defines routes and associates them with the corresponding controller functions.
  • Main App (app.js): Imports route files and uses them to handle requests.
  • This separation of concerns makes your code more modular, easier to test, and scalable as your application grows. Controllers encapsulate the application logic, making it more manageable and maintainable.

No comments:

Post a Comment