Skip to main content

Separating Controllers

Why we separate Controllers?​

Separating controllers in Express.js keeps the code organized and easy to manage. It helps with updating and scaling the app, improves code reuse and testing, and keeps different parts of the code separate. This also makes it easier for multiple developers to work on the app without interfering with each other.

How to create healthy endpoint with controller?​

  1. First create a folder in root directory by the name of controller.

  2. next create a file by the name of health.js in controller .

  3. Create a arrow function by the name of getHealth in health.js, and export it by named export

const getHealth = (req, res) => {
res.json({
success: true,
massage: "server is healthy",
});
};

export { getHealth };
  1. Import that function in index.js file which you have exported , in health.js file by the name of getHealth.
import { getHealth } from "./controller/health.js";
  1. Open index.js file and create a endpoint by the name of health and call that getHealth function
app.get("/health", getHealth);
  1. Now start the server by the command npm start and see in terminal your server is running on port 5000 .

  2. Now check it browser or in postman.

Postman output.​

Browser output​

Happy Coding 🤖​