likes
comments
collection
share

vue请求本地json文件,config.json配置动态地址,维护无需修改代码

作者站长头像
站长
· 阅读数 35

本地使用config.json

只需要把config.json文件放在static或webpack3生成的脚手架public里使用config.json文件时,dev或serve开发环境可以运行和使用,生产环境会报跨域错误。

{
    "BASE_URL":"www.baidu.com"
}

使用(main.js里):

import "../public/config.json"

//webpack3/4
import "../static/config.json"

生产环境

因为无法使用json了,换一种思路

在刚才config.json的地方新建config.js

const config = {
  path: "www.baidu.com", //接口地址
};
console.log(config);
sessionStorage.setItem('response', JSON.stringify(config));
console.log(JSON.parse(sessionStorage.getItem("response")).path)

使用(主入口文件index.html)

<script src="./config.js"></script>

在需要的地方

const path = JSON.parse(sessionStorage.getItem("response")).path