Create a Controller

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 286:- Create a Controller

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.

32. Beginning The Major Project 1

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support