Day-20: Backend Server Organizing with Routes and Controllers

Day-20: Backend Server Organizing with Routes and Controllers

#LearningExpressJS #Day20

On the 20th day of learning Express.js for backend development, I learned about the concept of creating routes and controllers to organize the structure of my application, making it more modular and easier to manage. This concept helps in making RESTful APIs in the future. Creating controllers and routes is a good practice for backend development as it organizes code, making it understandable, easy to explore, and easy to debug. This is the concept I explored today.


Routes in an Express Server

Routes are the definitions of the endpoints (URIs) in my web application. They determine how the server should respond to client requests for specific URLs. A route in Express.js typically includes:

·???????? Path: The URL pattern to match.

·???????? HTTP Method: The type of request (GET, POST, PUT, DELETE, etc.).

·???????? Handler Function: The function that gets executed when the route is matched.

Routes map incoming requests to specific controller functions. Essentially, a route is a URL pattern that triggers a specific function when a request matches it. This function, often called a route handler, processes the incoming request and sends an appropriate response.

Example:

const express = require("express");
const { demoFunction } = require("../controller/categoryController");

const router = express.Router();

router.get("/demo", demoFunction)

module.exports = router        

This line imports the router module defined in ./routes/categoryRoute. In main “server.js” file. This configures the Express application (app) to use the imported categoryRoute router for handling requests that start with /api. Any request to /api/* will be processed by the routes defined in categoryRoute.

?const categoryRoute = require("./routes/categoryRoute");

//routes
app.use("/api", categoryRoute);        

Controllers in an Express Server

Controllers are functions or classes that handle the logic for a specific route. They are responsible for processing the incoming request, interacting with the database if necessary, and returning a response. Using controllers helps to separate the route definitions from the business logic, making my code more organized and maintainable. A purpose of controller in Express.js typically includes:

  • Interact with databases or other data sources.
  • Process request data.
  • Perform calculations or validations.
  • Prepare response data.

Controllers house the business logic responsible for processing requests and generating responses. This separation of concerns enhances code organization, maintainability, and testability. Controllers are like the brain behind these routes. They contain the logic needed to handle the request and generate a response. When a route is matched, the corresponding controller function is called to process the request. This might involve interacting with a database, performing calculations, or formatting data before sending a response back to the client.

Example:

exports.demoFunction = (req, res) => {

    res.send("This is a demo message sent from the category controller");

};        

By using routes and controllers, our server-side Express.js code becomes easy to maintain and handle. It also helps to perform database operations easily and is useful for maintaining and operating RESTful APIs.


Introduction to RESTful APIs

A REST API (Representational State Transfer API) is a software architectural style for creating web services. It defines a set of rules for how applications can communicate over the internet. REST APIs use HTTP methods (GET, POST, PUT, DELETE) to perform actions like creating, reading, updating, and deleting data (CRUD operations). They are designed to be simple, scalable, and stateless, making them widely used for building modern web applications and services.

In essence, a REST API allows different applications to share data and functionality without needing to know the internal workings of each other. This makes it easier to integrate and interact with various web services, such as fetching data from a server or sending information to be processed. REST APIs are designed to be simple, scalable, and stateless, meaning each request from a client to a server must contain all the information needed to understand and process the request.

In a REST API, routers and controllers work together to manage and handle requests. The router directs incoming HTTP requests to the appropriate controller based on the URL and HTTP method, acting like a traffic cop. Controllers contain the logic to process these requests, interact with services or databases, and return the appropriate responses. For example, a request to “GET /users” would be routed to a “UserController”, which then handles the logic to fetch and return user data. This collaboration ensures that requests are efficiently managed and processed within the API.

?

In simple terms, a controller includes all the backend logic that can be performed according to HTTP requests, including the algorithms that should be executed for particular requests. Routes, on the other hand, accept or capture all HTTP requests that come to the server for certain operations and direct these requests to the appropriate controller. Essentially, a route shows the path where the request should go in the controller module and specifies the operation that should happen.

Routes and Controllers

Conclusion

Routes typically handle HTTP methods (GET, POST, PUT, DELETE) and URL patterns, while controllers interact with databases, process data, and prepare response data. By structuring an application with routes and controllers, developers create efficient, scalable, and well-structured codebases. By keeping routes and controllers separate, our code stays cleaner and more manageable. Routes handle the "where" and "how" of incoming requests, while controllers deal with the "what" and "why." This separation makes it easier to understand and maintain our code, especially as our application grows.


Instructor:

Bikash Karki

要查看或添加评论,请登录

Mahendra Mahara的更多文章

社区洞察

其他会员也浏览了