1

How you can have multiple nested routes in Express?

For example:

GET /api/v1/users
POST /api/v1/users
GET /api/v1/posts
POST /api/v1/posts
GET /api/v1/comments
POST /api/v1/comments

App.js

const apiBasePath = '/api';
const apiVersion = 1;
const apiVersionedPath = apiBasePath + '/v' + apiVersion + '/';

app.get(apiVersionedPath + 'users', ...);
app.post(apiVersionedPath + 'users', ...);
app.get(apiVersionedPath + 'posts', ...);
app.post(apiVersionedPath + 'posts', ...);
app.get(apiVersionedPath + 'comments', ...);
app.post(apiVersionedPath + 'comments', ...);

In Rails, there is a concept of 'scoped' URLs. Does something similar exists in Express? Not seeing it in the docs.

scope 'api' do:
  scope 'v1' do:
    get 'users', get_all_users
    post 'users', create_user
    ...
  end
end

There is a solution using middleware from 2014 here: Rest with Express.js nested router

Community
  • 1
  • 1
Don P
  • 60,113
  • 114
  • 300
  • 432

0 Answers0