vue 项目中 任意切换 request url (axios baseUrl)(Arbitrary switch request URL (Axios baseurl) in Vue project)

最近重构了一个项目,其中一个需求是每次切换菜单要换请求url

也尝试了其他方法,最终定为以下方案

此方案中用到了vuex,下载安装就不一一赘述了…

const service = axios.create({
  timeout: 5000,
});
// create中不设置baseUrl

service.interceptors.request.use(
  (config) => {
    // 对返回的数据进行一些处理
    var data = config;
    if (data.method === "get") {
      data.url = encodeURI(data.url);
    }
    if (data.url.indexOf("?") < 0) {
      data.url = data.url + "?t=" + Date.parse(new Date());
    } else {
      data.url = data.url + "&t=" + Date.parse(new Date());
    }
    config.headers["Accept-Language"] =
    Cookies.get("language") === "zh" ? "zh-cn" : "en-us";
    config.headers["Cache-Control"] = "no-cache";
    config.headers["Authorization"] = getToken();

    config.url = store.state.host + "/" + config.url; 
    // 直接修改请求url更方便
  // host 可以设置一个默认url 
    config = data;
    return config;
  },
  (error) => {
    console.log(error); // for debug
    Promise.reject(error);
  }
);

由于我们的需求是每次切换菜单更换url,所以在切换菜单这个方法里修改你要换的url就可以了

具体代码不做展示了,上面才是最重要的。

————————

Recently, a project was refactored. One of the requirements is to change the request URL every time the menu is switched

Other methods are also tried, and the following scheme is finally determined

Vuex is used in this scheme, so the download and installation will not be repeated one by one

const service = axios.create({
  timeout: 5000,
});
// create中不设置baseUrl

service.interceptors.request.use(
  (config) => {
    // 对返回的数据进行一些处理
    var data = config;
    if (data.method === "get") {
      data.url = encodeURI(data.url);
    }
    if (data.url.indexOf("?") < 0) {
      data.url = data.url + "?t=" + Date.parse(new Date());
    } else {
      data.url = data.url + "&t=" + Date.parse(new Date());
    }
    config.headers["Accept-Language"] =
    Cookies.get("language") === "zh" ? "zh-cn" : "en-us";
    config.headers["Cache-Control"] = "no-cache";
    config.headers["Authorization"] = getToken();

    config.url = store.state.host + "/" + config.url; 
    // 直接修改请求url更方便
  // host 可以设置一个默认url 
    config = data;
    return config;
  },
  (error) => {
    console.log(error); // for debug
    Promise.reject(error);
  }
);

Since our requirement is to change the URL every time you switch the menu, you can modify the URL you want to change in the switch menu method

Don’t show the specific code. The above is the most important.