Does anyone know of a way to configure express to add a prefix before all routes automatically? for example, currently I have:
/
/route1
/route2
However, I want to add a prefix like:
/prefix/
/prefix/route1
/prefix/route2
Right now I need to define prefix
manually to all of my routes but would like a more automated/configurable way. Can someone help?
Thanks in advance!
You can use the express Router() for this.
You can use the router like you would use your express app. So for example:
router.use(() => {}); // General middleware
router.get('/route1', () => {})
router.get('/route2', () => {})
router.post('/route2', () => {})
And then attach the router to your express app using:
app.use('/prefix', router);
https://expressjs.com/en/4x/api.html#router
routes.js
module.exports = (app) => {
app.post('/route', (req, res) => {
res.status(status);
res.send(data);
});
app.get('/route', (req, res) => {
res.status(status);
res.send(data);
});
return app;
};
Server.js
const router = express.Router()
const routes = require('./routes')(router, {});
app.use('/PREFIX_HERE', routes)
REFER : https://expressjs.com/en/guide/using-middleware.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With