Home > Enterprise >  Prefix all routes with string
Prefix all routes with string

Time:07-15

I'm trying to prefix all my routes with api/health. Here's the setup/code I have:

routes/food.js

const express = require('express')
const router = express.Router()
const foodController = require('../controllers/food');

router.get('/', foodController.getAllFood)

module.exports = router

routes/index.js

const foodRoute = require('./food');

module.exports = function (app) {
    app.use('/food', foodRoute)
};

And in /index.js I call require('./routes')(app);.

How can I make all routes have a prefix?

CodePudding user response:

If you want to keep your foodRoute modular (ie without hard-coding in the base path), you can pass it a router instead of the root app

// /index.js

const apiRouter = express.Router();
app.use("/api/health", apiRouter);

require("./routes")(apiRouter);
  • Related