簡體   English   中英

如何將 Heroku 生成的服務器端口應用到我的前端 Vue.js 應用程序?

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

這個問題類似於服務器和客戶端之間通信的更普遍的問題,但是這個問題可能是 heroku 特定的,因為服務器端口是由 heroku 在 'process.env.PORT' 變量中提供的。

我的后端 express/mongoDB 應用程序已部署在 heroku 上。 它偵聽分配的端口 = process.env.PORT,這是每次服務器啟動時的新端口

前端 Vue.js 運行在同一個 express 服務器上,使用 axios 進行 CRUD

我試過 port = process.env.PORT || Vue 應用程序中為 4000,但始終為 4000,因此請求失敗。

有沒有辦法將端口號從后端 Node.js 環境傳遞給 Vue.js 組件?

Vue.js 應用程序中似乎未設置 process.env.PORT

從示例 Vue 組件中提取

. . .

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' 段

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

非常感謝 Gowri 的出色響應,完全解決了問題。

對於遵循已經發布的許多教程的Vue新手,請注意在部署到heroku時需要使用相對路徑。 我的 MEVN 應用程序現在運行良好。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM