express icon indicating copy to clipboard operation
express copied to clipboard

Define middleware router at runtime (after app listen)

Open Tzvetelin88 opened this issue 1 year ago • 0 comments

Hello is it possible to define middleware routes after app is started?

app file:

const express = require('express');
const app = express();
var proxy = require('express-http-proxy');

import { aa } from './api';

const port = 3111;

// This working fine
app.use('/testRoute/1', proxy('http://localhost:55013'));

aa(app, '/defineRoute');

app.get('/', (req: any, res: any) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

api file for "aa" import:

import * as express from "express";
var proxy = require("express-http-proxy");

export function aa(app: express.Application, basePath: string) {
  const router = express.Router();
  app.use(basePath, router);

  router.get("/", async (req, res) => {
    // This not working :(
    app.use('/testRoute/2', proxy('http://localhost:55014'));

    res.send();
  });
}

When defining "/testRoute/1" it seems to work fine. After application is started, and I hit [GET] -> /defineRoute which should defines "/testRoute/2", but it seems not working

Tzvetelin88 avatar Aug 10 '22 14:08 Tzvetelin88

So express does not have any logic for route adding that varies from before or after app.listen is called. As far as Express is concerned there is no difference.

That said, that you for your example. I ran it and assuming I have a server at http://localhost:55014 your example is working fine for me.

Can you elaborate on what exactly you mean by "it seems not working"? Since that new route is a proxy, the response of it will depend on what is at http://localhost:55014

dougwilson avatar Aug 10 '22 14:08 dougwilson

I'm first sorry that I didn't brind more light to this. Example works indeed, as when we do not have proper route it brings:

Cannot GET /testRoute/2

and when we have it:

Error: connect ECONNREFUSED ::1:55013
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1237:16)
    at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17)

which is ok, as we have the route, but the service is not up on port 55013.

I found the problem with routing to be additional middleware added for 404 error:

app.use((req, res, next) => {
      const err = new HTTPError('Not Found', 404, ERROR_CODES.NOT_FOUND);
      next(err);
    });

when I remove this part everything works fine. So this is something not related to express and how it handles routing. We can close this issue.

Tzvetelin88 avatar Aug 10 '22 19:08 Tzvetelin88