简体   繁体   中英

Passing extra parameters to route handlers in Express

I'm relatively new to Express, and I'm looking for a way to make routes more reusable. In my app, I will have quite a few routes that can be passed to a generic handler, but will have different templates.

Example:

app.get('/about', function(req, res) {
    res.render('about.html');
});

app.get('/', function(req, res) {
    res.render('home.html');
});

While this example is contrite, I have 30+ such routes. What I would like to be able to do is something like this:

app.get('/about', generic.render('about.html'));

or otherwise somehow pass the template name to the function that returns res.render Is this possible in Express? All of my attempts to work around this result in variables being undefined.

I would prefer to not do something like this, tightly coupling my route parameters and template names:

app.get('/:template', function(req, res) {
    res.render(req.params.template + '.html');
});

You could just make aa simple middleware that does this for you. Example:

function simpleRender(file, opts) {
  opts || (opts = {});
  return function(req, res) {
    res.render(file, opts);
  };
}

Then just use it like:

app.get('/about', simpleRender('about.html'));

app.get('/', simpleRender('home.html'));

This is how I do it:

const handler = (req, res, template) => {
  res.render(template)
}

app.get('/about', (req, res) => {
  handler(req, res, 'about.html')
})

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