how to deploy nodejs api and vuejs app in one server

I found another way to deploy vue app and express/nodejs in one server without using PM. This what I did

  1. Build your vue code using npm run build command. This will create a folder dist which should have index.html file and static folder.
  2. Copy dist folder into your server code repository. In my case I created a folder public and moved the dist folder inside public.
  3. In app.js file right before module.exports=app line, copy the following lines of code

    //These 2 lines make sure that vue and express app are coming from the same server. app.use('/static', express.static(path.join(__dirname,"../public/dist/static/"))); app.get('/', function(req,res) { res.sendFile('index.html', { root: path.join(__dirname, '../public/dist/') }); });

First line make sure that the /static folder is accessible and second line will serve the index.html file when you run the node server. Routing between components will be taken care by vue.


This is how we are running our VueJS UI and ExpressJS REST API from the same server.

We are managing our services with PM2.

VueJS (Dev Environment, You can add the same settings to production)

In package.json add "start": "HOST='0.0.0.0' PORT=80 npm run dev",, where 80 is the port VueJS is listening on, to the "scripts": {..} array. Then, after installing PM2, (for dev) we can start VueJS with cd /location/of/vue/root; sudo pm2 start npm run dev --name Vue -- start. (Make sure that Apache is not running).

Please note that setting the HOST to 0.0.0.0 is important. Do not set it to LocalHost or your Servers IP address or you may run into issues.

ExpressJS

In the /location/of/express/app.js add this similar to the bottom of the file: app.listen(process.env.PORT || 8081), where 8081 is the port your REST API should be listening on. I can then start it with sudo pm2 start /location/of/express/app.js --name Express

At this point, the VueJS should be available at www.example.com (implied Port 80) and the REST API would be available at www.example.com:8081.

If you want to have api.example.com/ point to the API, you need to make sure that your DNS is pointing the "api" subdomain to the desired port, or you may have to add the port into the URL as above.

Additionally, you can easily follow the logs through PM2 as well with pm2 logs APPNAME --lines 100.