简体   繁体   中英

How to pass variable from route to controller Node.js JavaScript

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.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM