Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add prefix to all node / express routes

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!

like image 791
Trung Tran Avatar asked Nov 01 '17 16:11

Trung Tran


2 Answers

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

like image 180
Dominic Avatar answered Sep 28 '22 13:09

Dominic


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

like image 20
Anandan K Avatar answered Sep 28 '22 12:09

Anandan K