Search code examples
node.jsexpressswagger-ui

Can I override a route in Express?


If I do this:

app.get('/test', (req, res) => {
 res.send('First');
});

app.get('/test', (req, res) => {
 res.send('Second');
});

The first call is what works, the second get call does not override the first. Is there a good way to change that?

Basically I am working on a Swagger app where it can hit multiple APIs. I forked from https://github.com/thanhson1085/swagger-combined. The app knows if API A hits /user it will proxy any calls from /user to the appropriate place. Right now the app lists all API calls from as many APIs as you load. That means if API A & API B have the same endpoint of /user, I will only ever proxy to the first API that registered the endpoint in my app.


Solution

  • Express does not allow to override routes. But you should be able to use one and decide where to proxy those calls.

    app.get('/test', (req, res) => {
      if(req.isFirst()){
        res.send('First');
      }
      if(req.isSecond()){
        res.send('Second');
      }
    });
    

    It would probably better to have those apis in separate endpoints like /api1/user/ and api2/user/.

    You can basically pass Express Router into another Express Router.

    let api1Router = express.Router()
    rootRouter.use('/api1', api1Router)
    

    Hope that helps.