Reputation: 59
In the nodejs+express application can we have different routes files and include them into a single file. Like as below.
in hotel.routes.js I have few routes like
const express = require("express");
const hotelsCtrl = require("../controllers/hotels.controller");
const router = express.Router();
router
.route("/")
.get(hotelsCtrl.getAllHotels);
module.exports = router;
In the review.routes.js I have few routes like
const express = require("express");
const reviewsCtrl = require("../controllers/reviews.controller");
const router = express.Router();
router
.route("/")
.get(reviewsCtrl.getAllreviews);
module.exports = router;
Now I wanted to include both hotel.routes.js and review.routes.js in the index file and when the route is "/hotel" it should go to hotel.routes.js and when the route is "/review" it should go to review.routes.js
can someone please help in fixing this. Thanks in advance.
Upvotes: 0
Views: 65
Reputation: 707158
You can do this:
app.use('/hotel', require('./hotel.routes.js'));
app.use('/review', require('./review.routes.js'));
This puts the hotel.routes.js
exported router on /hotel
and the review.routes.js
exported router on /review
.
It seems like you've a bit over complicated things by using three files in order to set up a single /hotel
route.
You could also just do:
const hotelsController = require("../controllers/hotels.controller");
app.get('/hotel', hotelsController.getAllHotels);
There's really no need for the separate hotel.routes.js file.
Of, alternatively you could put the /hotel
in the hotel.routes.js
file like this:
const hotelsCtrl = require("../controllers/hotels.controller");
const router = require("express").Router();
router.get('/hotel', hotelsCtrl.getAllHotels);
module.exports = router;
And, then all you have to do in index.js
is this:
app.use(require('./hotel.routes.js'));
Upvotes: 1