1👍
I wanted to make a base url that will work under all scenarios or conditions regardless of the http/https protocols, port, localhost and actual domain whether it’s in development or it’s deployment/production.
So, I came up with this basic thing to handle local serve and build for production by using simple javascript.
Basics
var getUrl = window.location;
var baseUrl = getUrl.protocol + "//" + getUrl.host;
This base url will be computed on the runtime and decide the actual protocol and actual host name.
Advance
If you want to change the port for API calls for different ports with different microservices, you can also use this function
function changePortForAPI(baseUrl, port) {
var host = baseUrl.split("//");
var res = host[1].split(":");
res[1] = port;
var result = host[0]+"//"+res[0] +":"+ res[1];
return result;
}
Note: this ‘changePortForAPI(baseUrl, port)’ is for the development purposes because on build there is no use of port for API calls because it will be handled by server like Apache and Nginx etc.
SO, to detect localhost/development part and use different ports for API calls , you can use
function inDevelopment(baseUrl){
var index = baseUrl.indexOf("localhost");
if(index > 0){
return true;
}
else{
return false;
}
}
After the detection of development mode you can use "changePortForAPI" function for API calls that will run fine on development and deployment as well.
Edited:
function inDevelopment(baseUrl){
var host = baseUrl.split("//");
var index = host[1].indexOf(":");
if(index > 0){
return true;
}
else{
return false;
}
}
This edited function is fine when you consider to commit the changes and you are using network ip that is separate from other developer.