Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 482
Dave Stein Avatar asked Oct 26 '16 15:10

Dave Stein


People also ask

What is method override in Express?

Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it.

Are Express routes case sensitive?

Because Express routes are not case-sensitive, a request for /SECURE/manageInvoices will return the same resource as /secure/manageInvoices. However, the authentication-checking middleware will not be applied to /SECURE/manageInvoices, allowing an attacker to access the page without logging in.

How do routes work in Express?

A route is a section of Express code that associates an HTTP verb ( GET , POST , PUT , DELETE , etc.), a URL path/pattern, and a function that is called to handle that pattern.


1 Answers

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.

like image 113
Jakub Miziołek Avatar answered Sep 19 '22 14:09

Jakub Miziołek