If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To create a controller in an Express app, you can create a new file in the controllers
directory with a name that corresponds to the route you want to handle. For example, if you want to create a controller to handle requests to the /users
route, you can create a file called users.js
in the controllers
directory.
In this file, you can export an object that defines the functions to handle different HTTP requests. For example:
javascriptCopy code
const usersController = {
getUsers(req, res) {
// code to get users from database
res.send('List of users');
},
getUserById(req, res) {
const { id } = req.params;
// code to get user with given id from database
res.send(`User with id ${id}`);
},
createUser(req, res) {
const { body } = req;
// code to create user in database
res.send(`User created with name ${body.name}`);
},
updateUser(req, res) {
const { id } = req.params;
const { body } = req;
// code to update user with given id in database
res.send(`User with id ${id} updated with name ${body.name}`);
},
deleteUser(req, res) {
const { id } = req.params;
// code to delete user with given id from database
res.send(`User with id ${id} deleted`);
}
};
module.exports = usersController;
Then, in the routes.js
file, you can import the usersController
object and map its functions to the appropriate HTTP methods and routes using the express.Router
object. For example:
javascriptCopy code
const express = require('express');
const router = express.Router();
const usersController = require('./controllers/users');
router.get('/users', usersController.getUsers);
router.get('/users/:id', usersController.getUserById);
router.post('/users', usersController.createUser);
router.put('/users/:id', usersController.updateUser);
router.delete('/users/:id', usersController.deleteUser);
module.exports = router;
This sets up the routing for the /users
route and its subroutes using the functions defined in the usersController
object.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.