Adding new route is super easy because we have pre-defined code blocks in the boilerplate.
Add new route for users
- Create a route file in the app/routes directory named userRoutes.js
- Open server.js file
- Add two lines code in that file "import user's all routes" & "point all the routes to /user path"
JavaScript
Copyconst express = require('express'); const todoRoutes = require('./app/routes/todoRoutes'); const userRoutes = require('./app/routes/userRoutes'); // import users all routes const db = require('./app/utils/db'); const app = express(); const port = 3001; app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use('/todos', todoRoutes); app.use('/user', userRoutes); // and point all the routes to /user path app.listen(port, () => { console.log(`Server is listening on port ${port}`); });
Now add the api endpoint for /user routes in app/routes/userRoutes.js file
JavaScript
Copy// app/routes/todoRoutes.js const express = require('express'); const router = express.Router(); const userController = require('../controllers/userController'); router.get('/profile', userController.getUserProfile); router.post('/profile', userController.createProfile); module.exports = router;
Now there are two new endpoints added.
GET endpoint http://localhost:3001/user/profile to get user profile data
POST endpoint http://localhost:3001/user/profile to create a user profile in the database