Home > front end >  It is possible to have two apps running on the same port with expressjs?
It is possible to have two apps running on the same port with expressjs?

Time:08-01

It is possible to have two apps running on the same port with expressjs?

node app1.js:

const app = express();

app.get('/api/v1/foo', (req, res) => { res.json(...); });

express.listen(3000);

node app2.js:

const app = express();

app.get('/api/v1/bar', (req, res) => { res.json(...); });

express.listen(3000);

The endpoints are not collapse. But node say "the port in use".

Is it possible?

CodePudding user response:

const app = express();

app.get('/api/v1/bar', (req, res) => { res.json(...); });
app.get('/api/v1/foo', (req, res) => { res.json(...); });

express.listen(3000);

CodePudding user response:

You can put both in the same application like this:

const app = express();

app.get('/api/v1/bar', (req, res) => { res.json(...); });
app.get('/api/v1/foo', (req, res) => { res.json(...); });

express.listen(3000);

But you will not be able to run two applications on the same port. That's just how ports work.

CodePudding user response:

In addition to the correct reply from @Lalaluka:

If you want to run two applications on the same port and cannot put them in the same application for whatever reason, you can use a reverse proxy like NGINX. A reverse proxy is a server that sits in front of your web server (occupying the port) and directs traffic to the appropriate application.

https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/

CodePudding user response:

The answer from @Lalaluka is correct. I think the other way that you can run 2 apps in same port 3000, is by running 1 app using your IP address and the other one using localhost

app.listen(3000, "IP address") // http://ipaddress:3000/
app.listen(3000) // http://localhost:3000/

But only the app with IP address can be accessed in the network. Hope it helps. Thanks

  • Related