Home > database >  Passing express instance and route separation on two server files
Passing express instance and route separation on two server files

Time:06-22

I am trying to create a middleware to run two server files with same instance and trying to separate the routes. I will try to explain it the best way with examples:

Folder Structure:

/common-server
   /routers
     /routes.js
   /app1
     /server.js
     /index.html
   /app2
     /server2.js
     /index2.html
   /app.js
   /package.json

app.js:

const express = require('express');
const app       = express();
const routes    = require('./routers/routes');
PORT = 8005;

app.set('express', app);
app.use('/internal', routes);

app.listen(PORT, function() {
  console.log(`Application is listening on port ${PORT}`);
});

Here I am setting the express app instance to use the same on other server files.

routes.js

const express = require("express");
const router = express.Router();

router.get("/app1", (req, res) => {
    let appInstance = req.app.get('express');
    require('../app1/server')(appInstance);
});

router.get("/app2", (req, res) => {
    let appInstance = req.app.get('express');
    require('../app2/server2')(appInstance);
});

module.exports = router;

inside /app1/server I am just trying to send the html which belongs to this app and same goes for app2.

const path = require("path");
const staticDir = path.join(__dirname);

module.exports = function (server) {
  server.get("*", (req, res) => res.sendFile(path.join(staticDir, "index.html")));
};

The app seems to work fine for only one route which is http://localhost:8005/internal/app1 but when I am trying to switch between routes not getting any response from http://localhost:8005/internal/app2 and the page is getting loading endlessly.

Any suggestions what I might be doing wrong here?

CodePudding user response:

Something like this:

router.get("/app1", (req, res) => {
    let route = req.app.get('express');
    require('../app1/server')(route);
});

Can never work. What this is doing is when you get a /app1 incoming request, you're then registering another route handler, but not actually doing anything with the current request. You should be registering routes, once and only once. Then Express will match those routes and call the associated route handler.

If you just want to move route handlers to other files, then you can just make them regular functions and export them and then call them.

const { handler1 } = require('../app1/server');

router.get("/app1", (req, res) => {
    handler1(req, res);
});

Or, you can even just do this:

const { handler1 } = require('../app1/server');

router.get("/app1", handler1);

Then, inside of ../app1/server:

const path = require("path");
const staticDir = path.join(__dirname);

module.exports.handler1 = function (req, res) {
    res.sendFile(path.join(staticDir, "index.html"));
};
  • Related