简体   繁体   English

如何在已部署的Heroku节点应用程序上获取基本url变量

[英]How to get the base url variable on a deployed Heroku node app

I tried the following but it doesn't work: 我尝试了以下操作,但不起作用:

console.log(process.env.BASE_URL);   #output: undefined

Say my heroku app's host name is: https://RyanCameron-app.herokuapp.com 假设我的heroku应用的主机名是: https : //RyanCameron-app.herokuapp.com

How should I go about getting that base_url on heroku? 我应该如何在heroku上获取该base_url?

I am looking for a solution to avoid to respectively uncomment/comment out the following lines: 我正在寻找一种解决方案,以避免分别取消注释/注释以下行:

const url = 'https://RyanCameron-app.herokuapp.com/projects/eovendo' //production 
//const url = 'http://localhost:3000'                                //development

It has become quite annoying .. 变得很烦..

Backend 后端

This checks if you are in production or development mode and assigns the according url depending on the mode. 这将检查您是否处于生产或开发模式,并根据模式分配相应的url。

const production  = 'https://examplePage.com';
const development = 'http://localhost:3000/';
const url = (process.env.NODE_ENV ? production : development);

Explanation: process.env.NODE_ENV will resolve to undefined if you are running on localhost production mode . 说明:如果您在localhost 生产模式下运行, process.env.NODE_ENV将解析为undefined And return production if you have deployed the app production mode . 如果已部署应用程序生产模式,则返回production

Note : just because you have deployed the app doesn't necessarily mean you have changed the NODE_ENV 注意 :仅仅因为您已经部署了应用程序,并不一定意味着您已经更改了NODE_ENV


Frontend 前端

Make use of the javascript window to extract the url 利用JavaScript窗口提取网址

const url = window.location.origin;

You can use Base URL in JavaScript 您可以在JavaScript中使用基本网址

// This article: // https://stackoverflow.com/questions/21246818/how-to-get-the-base-url-in-javascript

var base_url = window.location.origin; // "http://stackoverflow.com"

var host = window.location.host; // stackoverflow.com

var pathArray = window.location.pathname.split( '/' ); // ["", "questions", "21246818", "how-to-get-the-base-url-in-javascript"]

Set a config variable, HEROKU_APP_NAME or HOST - something obvious. 设置配置变量HEROKU_APP_NAME或HOST-很明显。 You can access that in the backend but then you can also write it out into the DOM and have your front end access it from there. 您可以在后端访问它,但也可以将其写出到DOM中,并让前端从那里访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM