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
?​
First create a folder in
root directory
by the name ofcontroller
.next create a file by the name of
health.js
in controller .Create a arrow function by the name of
getHealth
inhealth.js
, and export it bynamed export
const getHealth = (req, res) => {
res.json({
success: true,
massage: "server is healthy",
});
};
export { getHealth };
- Import that function in
index.js
file which you have exported , inhealth.js
file by the name ofgetHealth
.
import { getHealth } from "./controller/health.js";
- Open
index.js
file and create aendpoint
by the name ofhealth
and call thatgetHealth
function
app.get("/health", getHealth);
Now start the server by the command
npm start
and see in terminalyour server is running on port 5000
.Now check it browser or in postman.