简体   繁体   中英

Combining several routes for API nodejs

I'm creating an API and have several routes. My folder structure looks like the following

-api
 -controllers
 -routes
  -videoRoutes
  -userRoutes
  -mainRoutes
 -server

Inside my routes are my API calls. Below is an example of my api routes in userRoutes

 module.exports = function(app) {
var user = require('../controllers/userController');

//user routes
app.route('/api/v1.0/users/getAllUsers')
    .get(user.getAllUsers);

app.route('/api/v1.0/users/login')
    .post(user.login);    

app.route('/api/v1.0/users/addUser')
    .post(user.addUser);

};

The game route follows a similiar structure layout. I want to have one main route which contains all the other routes and then just reference that in my server.js. To do this I have tried the following in the main routes folder

var mainRoutes = module.exports = function(app) {
require('./userRoutes');
require('./gameRoutes');
};

The in my server.js I have attempted to call the mainRoutes in the following way

 var routes = require('./api/routes/mainRoutes')
 routes(app);

However, this doesn't work and none of the API calls work when trying to call them on the front end. My code works fine as if I combine the two files (merging manually) it works but trying to combine using module exports seems to fail? What am I doing wrong? How can have the routes seperate in two js files and have a mainRouter and then just reference that in my server.js?

Also if this is bad practise or anyone has any suggestions of alternative methods please let me know.

It should work if you change your mainRoutes file to this:

var mainRoutes = module.exports = function(app) {
  app.use(require('./userRoutes'));
  app.use(require('./gameRoutes'));
};

Also, make sure you're exporting the router from the individual routes.

将您的代码更改为以下内容:

var mainRoutes = module.exports = function(app) { require('./userRoutes')(app); require('./gameRoutes')(app); };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM