使用 Javascript(开发、API 和生产)在前端制作基本 URL [英] Make Base URL at Frontend using Javascript (development, APIs and production)

查看:38
本文介绍了使用 Javascript(开发、API 和生产)在前端制作基本 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论开发和部署如何,如何制作适用于 http、https、localhost、端口和实际域的 base url?

How to make base url that works with http, https, localhost, port and actual domain regardless of the development and deployment?

推荐答案

我想制作一个可以在所有场景或条件下工作的基本 url,无论 http/https 协议、端口、本地主机和实际域是否正在开发中或者是部署/生产.

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.

所以,我想出了一个基本的东西,通过使用简单的 javascript 来处理本地服务和构建生产.

So, I came up with this basic thing to handle local serve and build for production by using simple javascript.

基础知识

var getUrl = window.location;
var baseUrl = getUrl.protocol + "//" + getUrl.host;

这个基本 url 将在运行时计算并决定实际的协议和实际的主机名.

This base url will be computed on the runtime and decide the actual protocol and actual host name.

前进

如果你想为不同的微服务的不同端口改变API调用的端口,也可以使用这个功能

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;
}

注意:这个'changePortForAPI(baseUrl, port)'是为了开发目的,因为在构建时没有使用端口进行API调用,因为它将由Apache和Nginx等服务器处理.

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,要检测本地主机/开发部分并使用不同的端口进行API调用,您可以使用

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;
    }
}

检测开发模式后可以使用changePortForAPI";用于 API 调用的函数,在开发和部署时也能正常运行.

After the detection of development mode you can use "changePortForAPI" function for API calls that will run fine on development and deployment as well.

function inDevelopment(baseUrl){
    var host = baseUrl.split("//");
    var index = host[1].indexOf(":");
    if(index > 0){
      return true;  
    }
    else{
      return false;
    }
}

当您考虑提交更改并且您使用与其他开发人员分开的网络 ip 时,此编辑功能很好.

This edited function is fine when you consider to commit the changes and you are using network ip that is separate from other developer.

这篇关于使用 Javascript(开发、API 和生产)在前端制作基本 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆