简体   繁体   English

将额外的参数传递给 Express 中的路由处理程序

[英]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.我对 Express 比较陌生,我正在寻找一种使路由更可重用的方法。 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.虽然这个例子很懊悔,但我有 30 多条这样的路线。 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?或以其他方式将模板名称传递给返回res.render的函数 这在 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')
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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