Alexus
Alexus

Reputation: 1973

simple proxy service in nodejs

As the title advises, I'm trying to create a simple proxy service in nodejs.

const express = require('express');
const proxy = require('http-proxy-middleware');

const app = express();

const auth = proxy({
  target: 'http://localhost:4200',
  ws: true
});

const game = proxy({
  target: 'http://localhost:4201',
  ws: true
});

app.use('/', auth);

app.use('/game', game);

app.listen(80, () => {
  console.log('Proxy listening on port 80');
});

However, only the auth route is being mapped correctly to / The game is not working at all and I'm wondering why exactly?

Is this approach correct or are there any other ways to achieve the expected route mapping?

Upvotes: 0

Views: 114

Answers (1)

Nipun Chawla
Nipun Chawla

Reputation: 366

Try this, it is working fine: Path rewrite is used for removing the /game part. If you will not use path rewrite then it will hit http://localhost:4201/game (with base path).

    const express = require('express');
    const proxy = require('http-proxy-middleware');

    const app = express();

    const auth = proxy({
      target: 'http://localhost:4200',
      ws: true
    });

    const game = proxy({
      target: 'http://localhost:4201',
      pathRewrite: {
        '^/game': '' // remove base path
      },
      ws: true
    });
    app.use('/game', game);
    app.use('/', auth); // route '/' should be in last

    app.listen(8080, () => {
      console.log('Proxy listening on port 80');
    });

Upvotes: 3

Related Questions