0

I'm using express 4.16 and I'm trying to keep my code tidy so I'm using the router feature. I've learned we can chain routers. Let's take this example :

./server.js:

var express = require('express');
var app = express();
var usersRoutes = require('./routes/users');
app.use('/users', usersRoutes);

app.listen(process.env.PORT || 3000);

./routes/user.js:

var express = require('express');
var router = express.Router();
var carsRoutes = require('./cars');
router.use('/cars', carsRoutes);
router
  .get('/:id', (req, res) => {
    // send back user info
  });
module.exports = router;

./routes/cars.js:

var express = require('express');
var router = express.Router();
router
  .get('/:id', (req, res) => {
    // send back car info
  });
module.exports = router;

So now we can call https//server.com/users/42 to get info on a user and https//server.com/users/cars/42 to get info on a car. But that's not really what I'm looking for in this case a https//server.com/cars/42 would be more appropriate. What if instead we want to implement this url https//server.com/users/42/cars to get all of users 42's cars, or https//server.com/users/42/cars/42 to get a specific car of users 42. How do you tell Express's router you want 'users/:id' too ?

Is this possible and if so how can we do it ? Or in this example should I just code users and cars routes in the same file and stop dividing into several .js files.

ashtrail
  • 93
  • 2
  • 9
  • In general, that types of URLs you're asking about don't really constitute good REST design so my first advice would be not not do both `https//server.com/users/cars/42` and `https//server.com/users/42/cars`. You could probably make it work by defining a route that uses a regex and looks for `https//server.com/users/ddd/cars` where `ddd` are some sequence of digits expressed in a regex. But, I wouldn't recommend it. Make your routes more declarative and non-conflicting. – jfriend00 Mar 27 '18 at 03:16
  • Exactly, I didn't plan on doing `https//server.com/users/cars/42` in the first place, I'm only interested in `https//server.com/users/42/cars/42`, I just don't know how to achieve that with router chaining. I only put the former as an example, although I can see now how that is confusing in my question, I edited it accordingly. – ashtrail Mar 27 '18 at 04:25

0 Answers0