Setting Up Routing for Todo List

Topic Overview and Actualization

Welcome to today's lesson! We'll be delving into routing, a crucial part of developing web applications. Think of a web application's routes like a system of roads in a city, guiding data from one part to another.

Our goal today is to grasp how to set up these "roads", known as routes, using Node.js and Express for a Todo List backend. It's like giving our web application a map to handle and organize data requests.

Here's our route map for today:

  1. Understand what routes are and why they matter.
  2. Learn how to set up routes for a Todo List.
  3. Learn to handle GET, and POST HTTP methods for our routes.

Ready to start your journey? Let's hit the road!

Understanding Routes

Routes in a web application are like street addresses. Imagine you're in New York City. Each building has its unique address so people can find it among the skyscrapers. Similarly, each part of your application has an address, known as a route.

Express.js, a framework for Node.js, makes creating these routes simple. An Express route is set up like this:

app.get('/todos', function(req, res) {
  res.send('GET route on todos.');
});

In this snippet, app is our Express server. get is the type of HTTP method we're responding to. '/todos' is the address for our route, and function(req, res) {...} is what we do when this route is visited.

Setting Up Route Handlers for GET and POST

After setting up our routes, we need to decide what happens when each route is visited. Going back to the city analogy, it's like deciding what each building in the city does. One might be the postal office, another the city hall, and a third the cinema. These decisions are made in route handlers, where we can specify the functionality for each route.

Let's start with an example for our GET route, where we want to return the list of all todos:

let todos = ["Finish Homework", "Go grocery shopping", "Prep for meeting"];

app.get('/todos', function(req, res) {
  res.send(todos);
});

In this route handler, req represents the incoming request data, and res is the object we can manipulate to send a response back. In this case, we've sent back our array of todos with the res.send() method. This allows the client to receive the current list of todos each time they visit this route.

Next, we need a way to store new information; after all, you cannot GET something if there is nothing to retrieve. This is done with the POST operation. Here’s a basic setup of our POST route:

app.post('/todos', (req, res) => {
});

As a server, we need to be able to comply with the requests sent to us, particularly for creating new todo items that have specific attributes. To easily access these parameters, we can instruct Express.js to automatically parse the JSON payloads into JavaScript objects by calling app.use(express.json()). This will provide us with a req.body to access the incoming data:

app.use(express.json());

let todos = [];

app.post('/todos', (req, res) => {
    const newTodo = {
        text: req.body.text,
        done: req.body.done
    };
    todos.push(newTodo);
    res.send(newTodo);
});

In this POST handler, we take in an object with text and done fields from the request body. We store the new todo in the server's array and send the newly created object back as a confirmation. Our backend can thus dynamically handle incoming data, keeping our todo list up-to-date. As more todos are added through POST requests, the server's array will grow, allowing for more comprehensive data retrieval with subsequent GET requests.

Finally, we can enhance our todos by giving each item a unique identifier for ease of access and control. This identifier can be set to the current time using Date.now() to avoid overlapping IDs:

app.use(express.json());

let todos = [];

app.post('/todos', (req, res) => {
    const newTodo = {
        id: Date.now(),
        text: req.body.text,
        done: req.body.done
    };
    todos.push(newTodo);
    res.send(newTodo);
});

Note that the id is automatically set by the server, ensuring that each todo item has a unique identifier without requiring the requester to provide it. This makes it easier to manage and reference each todo item individually.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal