
Hi folks, in the part 1 blog I shared the steps for setting and running up the node.js port. Today I want to continue this journey by creating routes. I choose theTodos app for which I'll write Create, Read, Update, and Delete (CRUD) todos APIs.
For this series, I'm following an excellent video tutorial fromTraversy Media
Table Of Contents
Create todosController
Create abackend
folder in your project and add acontrollers
folder in it.
All the features logic will go here with separate controller files. So now I'll add atodosController.js
file and create simple CRUD functions.
constgetTodos=(req,res)=>{res.status(200).json({message:'Get todos'})}constsetTodo=(req,res)=>{res.status(200).json({message:'Set todo'})}constupdateTodo=(req,res)=>{res.status(200).json({message:`Update todo${req.params.id}`})}constdeleteTodo=(req,res)=>{res.status(200).json({message:`Delete todo${req.params.id}`})}module.exports={getTodos,setTodo,updateTodo,deleteTodo}
I'll get theid
in the query param for update and delete todo API. I am just returning a static JSON message right now. I'll later replace it with the actual code.
Create a routes file
So now I'll add atodoRoutes.js
file inside/backend/routes
folder and initialize the router in it.
constexpress=require('express');constrouter=express.Router();const{getTodos,setTodo,updateTodo,deleteTodo}=require('../controllers/todosController')router.route('/').get(getTodos).post(setTodo)router.route('/:id').put(updateTodo).delete(deleteTodo)module.exports=router;
Connect route in server.js file
And inserver.js
file, I'll use this route like that
...// add these lines to accept req body for POST callapp.use(express.json())app.use(express.urlencoded({extended:false}))app.use('/api/todos',require('./routes/todoRoutes'))app.listen(port,()=>{...
P.S. Move your server.js file inside the backend folder. I didn't do it in the previous blog.
Now run the server and go to the postman and check your first route. It will give a result like this.
In the next blog, I'll connect the project with MongoDB and write the logic to add, update, delete and get todos.
Thank you for reading!
Feel free to connect onTwitter
Top comments(2)

- LocationDhaka
- EducationBSc in EEE
- WorkFront-End Developer
- Joined
I created a project structure throughexpress-generator and implemented the second part.
For further actions, you may consider blocking this person and/orreporting abuse