jeh
jeh

Reputation: 2443

Express js routes not working as expected with MEAN stack

I'm fairly new to express/mongoose and cannot work out why my routes are not working. I'm using the MEAN stack.

I have a general offer route '/offers' and then specific offer routes '/offers/television' and '/offers/laptops' but when trying to route to the specific routes it goes through '/offers' and not the routes I have written.

What am I missing?

Thanks!

My Code:

index.html

<a href="#!/offers/televisions">Television Offers</a>

config.js

    when('/offers',{
        templateUrl: 'views/offers/list.html'
    }).
    when('/offers/televisions',{
        templateUrl: 'views/offers/list.html'
    }).
    when('/offers/laptops',{
        templateUrl: 'views/offers/list.html'
    })

routes.js

 //Offer Routes
 var offers = require('../app/controllers/offers');
 app.get('/offers', offers.all); 
 app.get('/offers/televisions', offers.televisions); 
 app.get('/offers/laptops', offers.laptops); 

offers.js

/**
 * Find all offers
 */

exports.all = function(req, res){
console.log('all');
Offer.find({}, function(err, offers){
  if (err) {
    res.render('error', {
      status: 500
    });
  } else {
    res.jsonp(offers);
  }
});
};

/**
* Find all television offers
*/

exports.televisions = function(req, res){
  console.log('televisions');
  Offer.find({type: 'television'}, function(err, offers){
    if (err){
      res.render('error', {
      status:500
    });
  }else{
    console.log(offers);
    res.jsonp(offers);
  }
  });
};

Upvotes: 1

Views: 2129

Answers (2)

Luc Morin
Luc Morin

Reputation: 5380

Turning my comment into an answer:

You seem to define the same routes both in angular and in express, so when a route is hit within angular, the request won't be sent to the server.

You need to explicitly call the server route from your client code.

Cheers

Upvotes: 3

Jeff Escalante
Jeff Escalante

Reputation: 3157

More general routes should come after more specific ones. In this case, as soon as your router matches /offers, it's going to return that result, without getting to the more specific options below. If you rearrange your router as such:

 // Offer Routes
 var offers = require('../app/controllers/offers');
 app.get('/offers/televisions', offers.televisions); 
 app.get('/offers/laptops', offers.laptops); 
 app.get('/offers', offers.all);

It should resolve your issue as it matches the more specific routes before getting to the more general one : )

Upvotes: 2

Related Questions