Author Profile Altaf Shaikh
Altaf Shaikh

BE Engg | Python Dev | Content Writer | Founder of TeachMeBro | Blockchain Dev | Django

Todo App - Creating Routes and Controllers

January 26th 2021   343

Todo App - Creating Routes and Controllers
Todo App - Creating Routes and Controllers

We will see how to configure the routes and controllers together and also one request to you is keep a little more focus and have patience and faith in me : D, because from this point of time, you may lost, inside files and nothing will make sense to you what exactly is happening in the start so have patience, in the end everything will connect and make sense : )

So we will start with the routes, we have already defined our routes and their purpose.

Method

Path

Description

GET

/todos

Get all todos items

GET

/todos/:id

Get one todo item

POST

/todos

Create a new todo item 

PUT

/todos/:id 

Update a todo item

DELETE

/todos/:id

Delete a new todo item

 

As we can see in the table, we have 5 routes, so we will have 5 controllers. But there is one logical problem we have only 2 routes not 5, if you closely look at the Path column we only have /todos and /todos/:id and they are reused multiple times this is because we can future differentiate same route based on the HTTP methods ( GET, POST, PUT, DELETE, etc ). So you can see in the Method column, we have different HTTP methods for the same routes.

So let's start with the /todos route, this will return all tasks from database, now we will create a route and define the respective controller for it and then the process will repeat for other routes.

Create a todoRoutes.js file inside /routers folder we had created previously.

/todos/todoRouters.js

// import express
const express = require("express");


// controllers
const { getAllTodos } = require("../controllers/todoControllers");


// initialize route using express router
const todoRoute = express.Router();


// define the /todos + / => /todos/ route to get all todos
todoRoute
  .route("/")
  .get(getAllTodos);  // we will define and import this function soon



// export the route
module.exports = todoRoute;

Now, let's move onto the controller, create a todoControllers.js file inside /controllers and also now we will require our todo model we had created inside model/todos.js

/controllers/todoControllers.js

// import the todo model
const Todos = require("../models/todos");


const getAllTodos = (req, res) => {

 // mongoose find
  Todos.find({}) 

      .then((todos) => {

        res.status(200); // setting 200 ok  response status
        res.setHeader("Content-Type", "application/json");  // setting header as json
        res.json({ todos: todos });  // sending data to client in JSON 

      })
      .catch((err) => {

        res.status(500);   // setting 500 internal server error
        res.json({ error: err });   // sending error to client in JSON 

      });
};



// export the controllers
module.exports = {
  getAllTodos,
};


Now, lets link our router to our express app.

Open app.js file and import todoRouter from todoRouters.js :

//routes
const todoRouter = require("./routes/todoRoutes");



now, add the following line below your initialization of express app line 

.
.

const app = express();
.
.

app.use("/todos", todoRouter);

Updated app.js

// import express
const express = require("express");

//import mongoose
const mongoose = require("mongoose");

// import dotenv
const dotenv = require("dotenv");

// routers
const todoRouter = require("./routes/todoRoutes");


// load environment variable
dotenv.config({ path: ".env" });



// read env variable using process.env.<your_env_variable_name>
const PORT = process.env.PORT;
const dbURI = process.env.DATABASE_URL;


// making connection object
const connect = mongoose.connect(dbURI, {

  useNewUrlParser: true,
  useUnifiedTopology: true,

});


// connecting with database
connect.then(

  (db) => {
    console.log("Connected Successfully to Mongodb Server");
  },

  (err) => {
    console.log(err);
  }

);


// initialize express app
const app = express();


// sending a hello response on visiting http://localhost:3000/
app.get("/", (req, res) => {

  res
    .status(200)
    .json({ message: "Hi I am Server", data: "no data on this endpoint" });

});


app.use("/todos", todoRouter);


// listening for any HTTP requests on PORT 3000
app.listen(PORT, () => {

  console.log(`Server is running at http://localhost:${PORT}`);

});


Now if you visit http://localhost:3000/todos/ you should see the below response on your browser.

Output:

{"todos":[]}

Congratulations! You have created a your very own REST API backend : )

In next section, we will write routes and contollers for all the remaining Endpoints.