0

I have a project that is based on node and has Vue as a front-end.

In my app.js file in node I have

if(process.env.NODE_ENV === 'production'){
    //static folder
    app.use(express.static(path.join(__dirname,'public'))); 
    //handle SPA
    app.get(/.*/, (req, res)=>{
        res.sendFile(__dirname + '/public/index.html');
    });
}

and then

const port = process.env.PORT || 4000;
app.listen(port, ()=>{
    console.log('Server runs on port ', port);
});

So, node listens on port 4000 and all incoming requests (from port 4000) go to '/public/index.html' to get served by vue

In my vue.config.js I have

const path = require('path');

module.exports = {
    outputDir : path.resolve(__dirname, '..public'),
    devServer:{
        proxy:{
            '/*':{
                target:'http://localhost:5000'
            }
        }
    }
}

Everything works fine for now, but please help me understand the following

How can I have node listening to a port (eg 80) and then all other node api endpoints in another port (eg 4000) ?

I want all incoming requests to go to port 80, then still go to '/public/index.html', so Vue can take over.

But , the node endpoints Vue uses to GET and POST data , I want them to still be in port 4000, const basicUrl = 'http://awesomeness:4000/';

How can I do that ?

Thanks

codebot
  • 517
  • 8
  • 29
  • 55

1 Answers1

1

You may need to create 2 express App as shown in the link below :

NodeJS Express - separate routes on two ports

The first one will listen to port 80 and will return the index.html file.

The other one will listen to 4000 and handle request from your Vue app.

mJehanno
  • 836
  • 1
  • 12
  • 19
  • Thats a good idea, come to think of it, but how about one http server with two ports? Can node do that somehow? – codebot Feb 13 '20 at 13:57
  • 1
    it seems like a servr can only listen to one port so you have to create new server (basic node js)/app (expressJs) everytime you want to handle a different port. Yet you can create them in the same file. So you can have one nodeJs script that can handle multiple port throught different "servers"/"app". – mJehanno Feb 13 '20 at 14:02