So I have a user view and an admin view that are very similar except that an admin view can upload new data to my web app which displays different charts; thus I want to use the same controller that gets the data from the database.
In the controller, I need it to either render my user view or my admin view, so how can I pass that as a variable from the route to tell the controller which view to render.
For example, I have the normal /users route which all it does is
//users
router.get('/', uploadController.get_detail);
For the /admin route, it needs to first make sure that the credentials are valid and then render the same controller but pass in a different variable. This is because in the controller is where I have the :
// uploadController
res.render('VIEW', { title: 'Test', data: results });
And VIEW is where I want the variable to go. So if it came from /users route, then it was sent a variable 'users' and that would render my users.pug view. Same with the /admin route which would render my admin.pug view.
Routing with Express in Node: Express.js has an “app” object corresponding to HTTP. We define the routes by using the methods of this “app” object. This app object specifies a callback function, which is called when a request is received.
For exemple: /controllers/products.js Starting from my previous article here an exemple of a route and a controller file. As you can see the implementation is very easy and straightforward. Then import all the controller functions. Lastly, use the router object to create a route and controller association.
Using Framework: Node has many frameworks to help you to get your server up and running. The most popular is Express.js. Routing with Express in Node: Express.js has an “app” object corresponding to HTTP. We define the routes by using the methods of this “app” object.
"Routes" to forward the supported requests (and any information encoded in request URLs) to the appropriate controller functions. Controller functions to get the requested data from the models, create an HTML page displaying the data, and return it to the user to view in the browser. Views (templates) used by the controllers to render the data.
It looks like uploadController.get_detail()
is a middleware function right? So it has a signature that looks like:
uploadController.get_detail(req, res, next)
right?
The way you will normally handle passing data to middleware is to put a variable on res.locals
then the middleware can pick it up. For example:
router.get('/',
function(req, res, next){
res.locals.admin = true
next()
},
uploadController.get_detail
);
Then in get_detail()
you can read it off the res
object:
uploadController.get_detail(req, res, next) {
if (res.locals.admin) {
// do admin stuff
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With