-
Let us head back to our server folder and create our endpoints
-
our endpoints will be responsible for sending back data or taking care of any changes to our data from the frontend
- for example, we will be creating the end point /api/todos to send back all of our todos from the backend to the frontend
-
let us take advantage of the express router, which will help organize our code
- create a new file in our server fold called routes.js
-
paste in the following code
const express = require("express");
// create an instance of our router
const router = express.Router();
// GET /todos
router.get("/todos", (req, res) => {
res.status(200).json({ mssg: "GET REQUEST TO /api/todos" });
});
// POST /todos
router.post("/todos", (req, res) => {
res.status(201).json({ mssg: "POST REQUEST TO /api/todos" });
});
// DELETE /todos/:id
router.delete("/todos/:id", (req, res) => {
res.status(200).json({ mssg: "DELETE REQUEST TO /api/todos" });
});
// PUT /todos/:id
router.put("/todos/:id", (req, res) => {
res.status(200).json({ mssg: "PUT REQUEST TO /api/todos" });
});
module.exports = router;
- here we are creating four endpoints using the express router, let us go through each one
- GET /todos
- this is a GET request that as of right now sends a simple status code of 200 and a placeholder message of “GET REQUEST TO /api/todos”
- we will eventually use this route to send back an array of todos we will retrieve from our database
- POST /todos
- this is a POST request that as of right now sends a simple status code of 201 and a placeholder message of “POST REQUEST TO /api/todos”
- we will eventually use this route to take a todo from the front end and insert a new todo into our database
- DELETE /todos/:id
- this is a DELETE request that as of right now sends a simple status code of 200 and a placeholder message of “DELETE REQUEST TO /api/todos/:id”
- we will eventually use this route to take a todo id, and send a request to delete the todo that has that id
- we will be able to get the id using the :id parameter of our endpoint
- PUT /todos/:id
- this is a PUT request that as of right now sends a simple status code of 204 and a placeholder message of “PUT REQUEST TO /api/todos/:id”
- we will eventually use this route to take a todo id, and send a put request (in other words an update) to the todo that has that id
- we will be able to get the id using the :id parameter of our endpoint
<aside>
💡 Remark: the status codes we are using here are in a way arbitrary but these are standard status codes that are used with these respective CRUD operations
</aside>
- now open up our index.js and let us setup our routes, update your code to the following
const express = require("express");
const app = express();
// import our todos router
const router = require("./routes");
// use /api to prefix our endpoints
app.use("/api", router);
const port = 5000;
app.listen(port, () => {
console.log(`Server is listening on <http://localhost>:${port}`);
})