Home  >  Article  >  Web Front-end  >  How to unify the interface management of Vue and axios

How to unify the interface management of Vue and axios

不言
不言Original
2018-07-23 14:59:252264browse

It is very simple to request the interface through axios. If the axios request is encapsulated, the api can be configured as a method in only one place, and this method can be called directly when using it. Then there is no need to go to too much trouble.

But we don’t need to define each interface as a long-winded axios request method. Since we want to keep it simple, try to complete simple configuration in only one place.

1. Configure api interface

Put the interfaces of the same module under one file. For example, I defined a global.js under services in src as the global service configuration, in it The configured api can be used as a method of this service.

For example:

The name field will be used as the name of the method to be called later, but this is just a simple object. Now we define a method to convert it to method.

2. Convert the array object of the interface configuration into a method

import axios from "axios";

const withAxios = apiConfig => {
  const serviceMap = {};
  apiConfig.map(({ name, url, method }) => {
    serviceMap[name] = async function(data = {}) {
      let key = "params";      if (method === "post" || method === "put") {
        key = "data";
      }      return axios({
        method,
        url: "/api" + url,
        [key]: data
      });
    };
  });  return serviceMap;
};

export default withAxios;

We have defined a general method withAxios under utils. The function of this method is to convert the api configuration file into a method containing methods. an object.

3. Use withAxios

import withAxios from "../utils/withAxios";

const apiConfig = [
  {
    name: "userLogin",
    url: "/login",
    method: "get"
  },
  {
    name: "getUserInfo",
    url: "/login/user",
    method: "get"
  },
  {
    name: "getDeptList",
    url: "/login/department",
    method: "get"
  }
];

export default withAxios(apiConfig);

in the api configuration file to directly export the packaged object.

4. Use in vuex

If you want to call an api in vuex, first import the object just exported

import GlobalService from "@/services/global";

Call an interface in action:

const { data } = await GlobalService.userLogin(payload);

That's it. After that, only two steps of configuration and invocation are needed to complete the interface call, and the semantics of the interface are also clearer.

5. Other configurations of axios

We can make some general settings for axios in withAxios of utils.

For example, authentication is automatically included in each request header:

axios.defaults.headers.common["Authorization"] = getCookie("jwt") || "";// 注意:此处只会在web应用初始化时配置,在登录成功后需重新配置Authorization。

For example, using an interceptor to uniformly process the returned object:

axios.interceptors.response.use(response => {
  const { data } = response;  if (data.status === -2) {
    Vue.prototype.$Message.error(`无效的登录信息或登录已失效,请重新登录`);
    delCookie("jwt");
    router.push({ path: "/login" });
  }  if (data.status === -1) {
    Vue.prototype.$Message.error(`发生错误[${data.message}]`);
  }  return response;
});

Related recommendations:

How to deal with vue axios request timeout

The above is the detailed content of How to unify the interface management of Vue and axios. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn