0

I am working on a node project using express. I have some folders in the routes folder which include several .js files having routes. I want to keep the structure this way to keep my code neat & clear. How to require the routes in app.js file neatly?

  1. Seeing this, https://github.com/searsaw/express-routing-example/blob/master/app.js, I tried simply :
const routes = require('./routes');
app.use('/', routes);

but it doesn't work & brings my routes into action.

  1. Seeing this, I tried the require-dir method too, but it doesn't work as well. Nodejs Express: Routes in separete files

My folder structure is like :

-routes
    -admin
        -login.js
        -CRUD_event.js
        -CRUD_venue.js
     -client
         -login.js
         -CR_event.js
         -CR_venue.js

I don't want to mess my app.js file, I know all the routes can be required separately but that would be quite of just requiring code in app.js. I want to keep the route directory structure & require them in app.js in the most optimized way possible.

fight_club
  • 327
  • 4
  • 13

2 Answers2

1

You need to create an index.js file in the routes folder, as you are requiring the folder from your app.js, otherwise, it wouldn't know which file to look for. In this file (index.js), you need to specify routes for admins and clients and require them as needed.

In https://github.com/searsaw/express-routing-example/blob/master/app.js you can see that in every directory, there is an index.js file.

If you do not want to create an index.js file, you should specify the file name in the require statement.

0

I found where I am going wrong. This https://github.com/searsaw/express-routing-example/blob/master/app.js actually explains it all. In the routes folder, there is an index.js file requiring & using all other routes & then it is exported. It completely solves the problem.

fight_club
  • 327
  • 4
  • 13