最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the base url variable on a deployed Heroku node app - Stack Overflow

programmeradmin1浏览0评论

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:

How should I go about getting that base_url on heroku?

I am looking for a solution to avoid to respectively uncomment/comment out the following lines:

const url = '' //production 
//const url = 'http://localhost:3000'                                //development

It has become quite annoying ..

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

How should I go about getting that base_url on heroku?

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 ..

Share Improve this question edited Sep 1, 2018 at 16:07 Ryan Cameron asked Sep 1, 2018 at 15:59 Ryan CameronRyan Cameron 3712 gold badges5 silver badges16 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

Backend

This checks if you are in production or development mode and assigns the according url depending on the mode.

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. And return production if you have deployed the app production mode.

Note: just because you have deployed the app doesn't necessarily mean you have changed the NODE_ENV


Frontend

Make use of the javascript window to extract the url

const url = window.location.origin;

You can use Base URL in 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. 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.

发布评论

评论列表(0)

  1. 暂无评论