rap-2-h
rap-2-h

Reputation: 31978

Express router matching params

Assuming I have two routes one with params, one without:

I want to use two different handlers for these two routes. I know I can do something like this.

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

But, it would make the code harder to read. Is there a way to match a route that has a parameter? I would like to manage this situation:

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

Upvotes: 1

Views: 1068

Answers (2)

Zeeshan Hassan Memon
Zeeshan Hassan Memon

Reputation: 8325

How about this?

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

Upvotes: 0

artX
artX

Reputation: 131

As far as I know, queries can not be filtered on use handler. Instead, I made out with the very similar situation by using 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 this document may also help you

Upvotes: 1

Related Questions