Building the add Todo API request

We'll also need to be able to create new Todos. To do that, we'll implement the next portion of our API, where we will create a route in server.js that is able to handle receiving an HTTP post with a body. Remember that line of code from earlier, where we instructed express to use the JSON middleware? The code for this isn't very complicated either. We specify to express that we can accept an HTTP post and give it the standard req, res arguments.

From there, since we only have a few items in our Todo list, we give the new Todo an id of the length of that list plus one, and then we fill it up with the rest of the body that is passed in by the user, using the object spread operator! As follows:

app.post("/api/todos", (req, res) => {
const body = { id: todos.length + 1, ...req.body };
res.json({ todos: [...todos, body] });
});

Again, to verify that we're doing things correctly, we'll send a quick test via Postman with a Todo body and verify that we get sent back the list of Todos, plus the new one that we post in! Refer to the following screenshot:

That's all we need to add a new Todo, so now we can move on to the next piece of functionality: deleting a Todo!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.122.195