Search code examples
node.jsexpressherokuvue.js

How can I apply the Heroku generated server port to my front-end Vue.js app?


This problem is similar to a more general question of communicating between server and client, however the issue is probably heroku specific because the server port is provided by heroku in the 'process.env.PORT' variable.

My back-end express/mongoDB app has been deployed on heroku. It listens on the assigned port = process.env.PORT which is a new port every time the server starts

The front end Vue.js runs on the same express server and uses axios for CRUD

I have tried port = process.env.PORT || 4000 in the Vue application but it is always 4000 so the request fails.

Is there some way to pass the port number from the backend Node.js environment to Vue.js components ?

It appears that process.env.PORT is not set in the Vue.js application

Extract from a sample Vue component

. . .

import port from '../config';
export default {
  data() {
    return {
      tokens: []
    };
  },
  created() {
    let uri = 'http://localhost:' + port + '/tokens';
    this.axios.get(uri).then(response => {
      this.tokens = response.data;
    });
  }
};

. . .

'config.js'

const port =  process.env.PORT || 4000;

export default port;

'server.js' segment

const PORT = 4000;
const port = process.env.PORT || PORT
app.listen(port, () => {
    console.log('Express server running on port ' + port);
});

Solution

  • Thanks very much to Gowri for an excellent response that completely fixed the problem.

    For newcomers to Vue who follow the many tutorials that have been published, please take note of the need to use a relative path when deploying to heroku. My MEVN app is now working perfectly.

    export default {
      data() {
        return {
          tokens: []
        };
      },
      created() {
        let uri = '/tokens';
        this.axios.get(uri).then(response => {
          this.tokens = response.data;
        });
      }
    };