Express路由器匹配参数

Express router matching params

假设我有两条路线,一条有参数,一条没有:

我想为这两条路线使用两个不同的处理程序。我知道我可以做这样的事情。

app.use('/foo', (req, res) => {
  if (req.params.foo !== undefined) {
    // do something
  } else {
    // do something else
  }
})

但是,这会使代码更难阅读。有没有办法匹配具有参数的路由?我想处理这种情况:

app.use('/foo', x);
app.use('/foo?bar', y);

据我所知,无法在 use 处理程序上过滤查询。 相反,我通过使用 next 来解决非常相似的情况。

app.use('/foo', (req, res, next) => {
    if (req.query.foo !== undefined) return next(); 
    //if foo is undefined, it will look for other matching route which will probably the next '/foo' route


    /* things to do with foo */
});

app.use('/foo', (req, res) => {
   //things to without foo
});

https://expressjs.com/en/guide/using-middleware.html 本文档也可能对您有所帮助

这个怎么样?

const express = require('express');
const app = express();

// curl -X GET http://localhost:3000/foo
app.get('/foo', function (req, res, next) {
    res.send('This is foo');
});

// curl -X GET http://localhost:3000/foo/bar
app.get('/foo/:?bar', function (req, res, next) {
    res.send('This is foo with bar');
});

app.listen(3000);