快速路由器匹配参数

时间:2020-03-10 14:49:49

标签: javascript node.js express router

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

  • / foo?bar
  • / foo

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

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);

2 个答案:

答案 0 :(得分:1)

据我所知,查询无法在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 该文档也可能对您有帮助

答案 1 :(得分:0)

怎么样?

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);