[英]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.这个问题类似于服务器和客户端之间通信的更普遍的问题,但是这个问题可能是 heroku 特定的,因为服务器端口是由 heroku 在 'process.env.PORT' 变量中提供的。
My back-end express/mongoDB app has been deployed on heroku.我的后端 express/mongoDB 应用程序已部署在 heroku 上。 It listens on the assigned port = process.env.PORT which is a new port every time the server starts它侦听分配的端口 = process.env.PORT,这是每次服务器启动时的新端口
The front end Vue.js runs on the same express server and uses axios for CRUD前端 Vue.js 运行在同一个 express 服务器上,使用 axios 进行 CRUD
I have tried port = process.env.PORT ||我试过 port = process.env.PORT || 4000 in the Vue application but it is always 4000 so the request fails. Vue 应用程序中为 4000,但始终为 4000,因此请求失败。
Is there some way to pass the port number from the backend Node.js environment to Vue.js components ?有没有办法将端口号从后端 Node.js 环境传递给 Vue.js 组件?
It appears that process.env.PORT is not set in the Vue.js application Vue.js 应用程序中似乎未设置 process.env.PORT
Extract from a sample Vue component从示例 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' 'config.js'
const port = process.env.PORT || 4000;
export default port;
'server.js' segment 'server.js' 段
const PORT = 4000;
const port = process.env.PORT || PORT
app.listen(port, () => {
console.log('Express server running on port ' + port);
});
Thanks very much to Gowri for an excellent response that completely fixed the problem.非常感谢 Gowri 的出色响应,完全解决了问题。
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.对于遵循已经发布的许多教程的Vue新手,请注意在部署到heroku时需要使用相对路径。 My MEVN app is now working perfectly.我的 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.