Search code examples
node.jsmeteorroutesiron-router

iron-router routes with same root path in meteor


I'm new in Meteor and iron-router.

I need this two route:

/movie/:title
&
/movie/title?q=queryText

This is my route code (/server/myRoute.js):

// http://localhost:3000/movie/MovieTitleHere
// Result Output: Route 1 (correct)
Router.route('/movie/:title', function() {
    var res = this.response;
    res.end("Route 1");
}, { where: 'server' });

// http://localhost:3000/movie/title?q=queryText
// Result Output: Route 1 (incorrect)
Router.route('/movie/title', function() {
    var res = this.response;
    var query = this.params.query;
    var searchQuery = query.q;
    res.end("Route 2" + searchQuery);
}, { where: 'server' });

But always first route fired, how to set this??

I want any override solution to override first route.

I didn't find anything about this in iron-router documentation.

Edit:

@Tom solution is OK but what to do if I want to organize this two route in two separate file? (for example route1.js and route2.js)


Solution

  • I think you just need to declare the more specific route first, ie /movie/title/:title

    Have that first in your code and you should be good.

    In response to your edit, your code should be the other way around I believe:

    // http://localhost:3000/movie/title?q=queryText
    // Result Output: Route 1 (incorrect)
    Router.route('/movie/title', function() {
      var res = this.response;
      var query = this.params.query;
      var searchQuery = query.q;
      res.end("Route 2" + searchQuery);
    }, { where: 'server' });
    
    // http://localhost:3000/movie/MovieTitleHere
    // Result Output: Route 1 (correct)
    Router.route('/movie/:title', function() {
      var res = this.response;
      res.end("Route 1");
    }, { where: 'server' });
    

    As you have it written, /movie/:title is saying match /movie/ followed by anything. As the word 'title' falls within the broad subset of 'anything' you are never getting to the second route.

    Instead, having it the other way around has the more specific route first.

    Hope that makes sense!