0

I have 2 apps I am looking to add to my profile website which itself is an express app.

I want to run these apps under a /projects route such that we can have localhost/projects/app1 and localhost/projects/app2

I want all the sub routes for each app to be handled at their respective routes e.g the route /projects/app1/signup redirects after a successful POST to the dashboard but now i need to make sure this does not redirect to localhost/dashboard but instead localhost/projects/app1/dashboard

I am aware of routing and I ams also using it on App1 i.e

var rank = require('./routes/ranks');
...
var taxiRanks = new rank();
...
app.get('/',taxiRanks.findNearbyRanks);
app.get('/whereami',taxiRanks.getCurrentLocation )
app.post('/location',taxiRanks.receiveLocation) 
app.post('/signup',taxiRanks.newUser)

I WANT TO ACHIEVE SOMETHING LIKE THIS

...
var main_app = express()
var app1 = require('./path/to/app1')
var app2 = require('./path/to/app2')
...
main_app.get('/projects/app1' , app1())
main_app.get('/projects/app2' , app2())
Ayabonga Qwabi
  • 306
  • 5
  • 12

1 Answers1

4

You can use the Router API of Express :

// app1.js
const app1Routes = express.Router();

app1Routes
  .use('/user', userRoutes)
  .use('/activity', activityRoutes)

module.exports = app1Routes;


// app2.js
const app2Routes = express.Router();

app2Routes
  .use('/food', foodRoutes)
  .use('/candy', candyRoutes)

module.exports = app2Routes;

// app.js
const app1Routes = require('./app1.js');
const app2Routes = require('./app2.js');

app.use('/app1', app1Routes);
app.use('/app2', app2Routes);

And for example in userRoutes you could declare your routes like that :

const routes = express.Router();

routes.get('/:id', (req, res) => res.status(200).send({ id : 1, firstName : 'junk' }));

routes.post('/', (req, res) => res.status(201).send({ msg : 'User created' }));

module.exports = routes;
MatthieuLemoine
  • 718
  • 6
  • 11