Tutorial
Routes & Controllers

Setup Routes & Controllers using Express Routers

Setup Routes

▶️ Basic Setup

  1. Create a new folder using the command mkdir routes in the root directory of your project.

routes decide the path where the request will be sent to the server.

  1. Create another folder mkdir controllers in the root directory of your project.

controllers decide the action to be taken when the request is received by the server.

  1. Go under controllers folder using the command cd .\controllers\ and create a new file echo > task.js to create a new file named task.js also do this for routes folder.

▶️ Setup task.js (routes)

Open routes folder and create a new file named task.js echo > task.js and open it.

  1. Importing the express module and creating a router object using the express.Router() method.
const express = require('express');
const router = express.Router();
  1. Eoute to get all the tasks.
router.route('/').get(getAllTasks);
  • We will create a testing route to check if the route is working or not.
router.route('/testing').get(getAllTasksTesting);

Yet we have not created the getAllTasksTesting function. We will create it later. This means when someone visit localhost:5000/tasks/testing, the getAllTasksTesting function will be called.

  1. Exporting the router object.
module.exports = router;

▶️ Setup task.js (controllers)

  1. Create a getAllTasks function.
  • getAllTasks using an arrow syntax (=>), which is a shorter way of writing functions in JavaScript and the function has two parameters: req and res, which stand for request and response. These are objects that represent the incoming and outgoing data of a web server.
  • The function is marked as async, which means it can run asynchronously without blocking other code. This allows you to use await inside the function to wait for promises
  • A promise is an object that represents an asynchronous operation that may succeed or fail. For example, fetching data from a database or an API is an asynchronous operation that returns a promise.
  • The function body has one statement: res.status(200).json({ msg: 'Show all tasks' });. This statement sends a response with two things:
    • A status code of 200, which means OK.
    • A JSON object with a message “Show all tasks”. JSON stands for JavaScript Object Notation and it is a format for exchanging data between different systems.
const getAllTasks = async(req, res) => {
    res.status(200).json({ msg: 'Show all tasks' });
  };
  1. Create a getAllTasksTesting function.
const getAllTasksTesting = async(req, res) => {
    res.status(200).json({ msg: 'Show all tasks testing' });
  };
  1. Exporting the getAllTasks and getAllTasksTesting functions.
module.exports = {
    getAllTasks,
    getAllTasksTesting
  };

▶️ Importing Controllers in Routes

  1. Importing the getAllTasks and getAllTasksTesting functions from the controllers/task.js file.
const {
    getAllTasks,
    getAllTasksTesting
} = require('../controllers/task');

▶️ Middleware to Set Router

  1. Setting the router to the path /api/tasks and all the routes will be set under this path.
app.use("/api/tasks");

Here we are setting the router to the path /api/tasks and all the routes will be set under this path and app.use() is a middleware function in Express. It is used to set the router object in the Express application and router object is used to define the routes of the application.

  1. tasks_routes function is called when the path is /api/tasks and the router object is passed as a parameter to the function.
const tasks_routes = require("./routes/task");
 
 
app.use("/api/tasks", tasks_routes);

If you now run the server using npm run dev and visit localhost:5000/api/tasks/testing in your browser, you should see the message “Show all tasks testing” in the browser or visit localhost:5000/api/tasks in your browser, you should see the message “Show all tasks” in the browser.

That’s it! We have successfully created the routes and controllers using express routers this is some kind of api setup.