项目中用运行时 config.json 动态配置后端地址(精华版)

文章目录


前言

局域网多现场部署(每个项目后端 IP 不同),但不希望每次打包都改 .env 或重建。目标是:运行时可配置 API_BASE_URL,前端无需重打包即可切换后端地址

把可变的后端地址放到 public/config.json(运行时文件),启动时读取并缓存;axios 在请求时从缓存读取 API_BASE_URL 并注入到每次请求的 baseURL 中


无需重打包:部署时只改 dist/config.json。

兼容浏览器部署:不用改路由器或 DNS

支持现场临时覆盖(localStorage):方便运维即时调试。

简单、工程化、易维护。`

一、public/config.json(部署时修改)?

javascript 复制代码
{
  "API_BASE_URL": "http://192.168.1.100:8080"
}

放在 public/,打包后会原样复制到 dist/config.json,浏览器可通过 /config.json 读取。

二、main.js(运行时加载 + 缓存)

1、代码

javascript 复制代码
import Vue from 'vue'
import App from './App.vue'
import router from "@/router"
import axios from "axios";
import store from './store/index';
import scroll from 'vue-seamless-scroll'
// import getMqttClient  from '@/utils/mqttClient';
import { loadRuntimeConfig } from '@/utils/config' 
Vue.prototype.$store = store
import '../src/plugins/element'
Vue.use(scroll)

Vue.prototype.$axios = axios
// const mqttClient = getMqttClient({ clientId: "dp_" + store.state.login.publickey });
// const mqttClient = new MQTT({
//   topic: `zh-ylgl/dsj/${this.login.privatekey}`,
//   clientId: "dp_" + this.login.publickey,
// });
// mqttClient.init();
// 连接 MQTT 并订阅指定的主题
// mqttClient.link();
// Vue.prototype.$mqttClient = mqttClient;
Vue.config.productionTip = false
loadRuntimeConfig().then(() => {
  new Vue({
    router,
    store,
    render: h => h(App),
  }).$mount('#app')
})

2.引入

javascript 复制代码
// src/utils/config.js
let runtimeConfig = null

export function loadRuntimeConfig () {
  return fetch('/config.json?_=' + Date.now())
    .then(res => res.json())
    .then(cfg => {
      runtimeConfig = cfg
      return cfg
    })
}

export function getRuntimeConfig () {
  return runtimeConfig || {}
}

3、使用

javascript 复制代码
// utils/request.js
import axios from 'axios';
import { Message } from 'element-ui'; // 引入 Element UI 的消息组件
import { getRuntimeConfig } from '@/utils/config'



// 创建 axios 实例
const instance = axios.create({
  timeout: 5000,
});

// 请求拦截器
instance.interceptors.request.use(config => {
    const cfg = getRuntimeConfig()
  if (cfg && cfg.API_BASE_URL) {
    config.baseURL = cfg.API_BASE_URL
    console.log("cfg.API_BASE_URL: ", cfg.API_BASE_URL)
  }
  return config
}, error => {
  // Message.error('请求错误: ' + error.message); // 替换为 Element UI 消息提示
  return Promise.reject(error);
});

// 响应拦截器
instance.interceptors.response.use(
  response => {
    const data = response.data;
    if (data && !data.Status) { // 判断 Status 是否为 false
      // Message.error(`Error: ${data.Message || 'Unknown error'}`); // 使用 Element UI 消息提示
      return data;;
    } else {
      return data; // 返回整个响应数据
    }
  },
  error => {
    if (error.response) {
      // 处理服务器返回的错误响应
      // Message.error(`Error code ${error.response.status}: ${error.response.statusText}`);
    } else {
      // 处理网络问题
      // Message.error('No response from server');
    }
    return Promise.reject(error);
  }
);

export default instance;

四、部署与使用说明

打包项目生成 dist 目录

修改 dist/config.json 中的 API_BASE_URL

刷新页面即可生效,无需重新打包

五、总结

通过引入运行时 config.json,将后端 IP 配置从构建期迁移到运行期,彻底解决了局域网多项目部署频繁改包的问题。

相关推荐
灵析表格11 小时前
json_ObjectToKV 函数:Excel解析JSON对象的权威方案
json·excel
灵析表格11 小时前
灵析表格文本处理函数技术白皮书:WPS Excel 官方函数扩展库 18 项文本规整与正则批处理企业落地标准
ai·json·excel·wps
桑榆4161 天前
JSON 格式
json
fchen5211 天前
JSON:一站式开发者工具集,SQL日志解析并填充 、JSON格式化 与文本比对
sql·microsoft·json
小当家.1051 天前
LLM结构化输出与流式响应:从JSON修复到SSE全链路
llm·json
前网易架构师-高司机2 天前
带标注的羽毛球运动员,裁判,羽毛球识别数据集,识别率84.4%,2879张图,支持yolo,coco json,voc xml,文末有模型训练代码
xml·yolo·json·数据集·羽毛球·裁判
leisoo80972 天前
股票数据本地化存储实战:JSON、数据库与列式存储的方案对比
jvm·数据库·json
切糕师学AI2 天前
从压缩到查询:PostgreSQL中JSON数据的存储与处理实践
数据库·postgresql·json
doubt。2 天前
大模型prompt工程Zero-Shot与Few-Shot以及json格式
人工智能·深度学习·机器学习·语言模型·json·prompt
烟锁池塘柳03 天前
Conda 创建环境报错:Unable to read repodata JSON file,清华源 pkgs/free 失效解决方法
json·conda