zireael9797
zireael9797

Reputation: 103

Handling different routes that start similarly in NodeJS, Express

I'm creating an API which have Articles and Comments belonging to those articles.

const articleRoutes = require('./api/routes/articles');
const commentRoutes = require('./api/routes/comments');

then

app.use('/articles', articleRoutes);
app.use('/comments', commentRoutes);

Anything starting with "articles/" gets forwarded to articleRoutes, and anything starting with "comments/" gets forwarded to commentRoutes. Comment GET requests are like

/comments?article=ID_OF_ARTICLE

Like this everything is working perfectly.

However I want to restructure the comments route to be like

/articles/ID_OF_ARTICLE/comments

However now they both start with "/articles"

How would I deal with this?

Upvotes: 0

Views: 104

Answers (2)

zireael9797
zireael9797

Reputation: 103

The originalUrl approach seems to work too, But I went with the solution here

Apparently I can do

app.use('/articles/:articleId/comments', function(req, res, next) {
    req.articleId = req.params.articleId;
    next();
}, commentRoutes);

and in commentRoutes

// in commentRoutes
router.get('/', (req, res, next) => {
    let articleId = req.articleId
})

So I can attach the required parameter to the request as a separate entry and access it directly

Upvotes: 1

I would try the following:

app.use('/articles/:id/comments', commentRoutes);
app.use('/articles', articleRoutes);

So I think the order is important in the above.

// inside commentRoutes
Router.get('/', (req, res) => {
  let articlesId = req.originalUrl.split('/')[2]
})

I hope this helps

Upvotes: 1

Related Questions