0

I've two app.use statements and would like to use each for different routes.

        app.use(function(request, response, next){  //also has /sessions/:id etc.
            if(request.url.indexOf("/sessions") == 0) {
                console.log('in sessions', request.url); //executes for both routes
            } else {
                next();
            }
        });


        app.use(function(request, response, next){
            if(request.url.indexOf("/sessions-speakers") == 0) {
                console.log('in sessions speakers', request.url);
            } else {
                next();
            }
        });

but the problem is with checking url is that first app.use and it's condition gets true in both cases, I'm wondering what can I use to branch there based on the routes.

Expectation:

Work out something using if statement in app.use to branch out between the two requests.

user2727195
  • 7,122
  • 17
  • 70
  • 118
  • Have you taken a look at this: http://expressjs.com/guide/using-middleware.html – Zachrip May 30 '15 at 02:15
  • this sounds promising, I was doing it wrong... – user2727195 May 30 '15 at 02:16
  • question, what if I've two routes within one uri, like `app.get("/sessions"` and `app.get("/sessions/:id"`, seems like I've to specify `app.use` for both of them individually, before I was re-using one `app.use` with `if` to work for both – user2727195 May 30 '15 at 02:18
  • Well, if I were you that's the way I would handle it to begin with. Don't worry if there's another app.use, in the end your code is more organized. – Zachrip May 30 '15 at 02:25
  • thanks for pointing in the right direction.... :) – user2727195 May 30 '15 at 02:42

1 Answers1

0

A good way to get your head around doing something new is to check out the docs for the function you're trying to use. In this case, that is app.use. Here are the official docs for it. Understand the function signature, and the tutorials you encounter will make more sense. In this case, you seem to want to use a single statement and 'branch' the routes.

Try:

Calling the function with a string first, like so:

  app.use("/sessions", function(request, response, next){  
    console.log('in sessions', request.url); //both
    if(request.url.indexOf("/sessions-speakers") == 0) {
      console.log('in sessions speakers', request.url);
    } else {
      next();
    }
  });  

Here's the pattern:

String | Function | Server route, callback or server
Function | Server callback or server
returns Server for chaining

This is not super clean, but does the job. Make sure you understand what is happening in each line of code before refactoring though. For example, what does next() do?

Community
  • 1
  • 1
Sze-Hung Daniel Tsui
  • 2,282
  • 13
  • 20