import{_ as s,o as n,c as a,R as l}from"./chunks/framework.6241eaf2.js";const C=JSON.parse('{"title":"Axios 封装及接口管理","description":"","frontmatter":{},"headers":[],"relativePath":"guide/vue2/axios.md","filePath":"guide/vue2/axios.md","lastUpdated":1731315864000}'),o={name:"guide/vue2/axios.md"},p=l(`

Axios 封装及接口管理

utils/request.js 封装 axios ,开发者需要根据后台接口做修改。

javascript
import axios from "axios";
import store from "@/store";
import { Toast } from "vant";
// 根据环境不同引入不同api地址
import { baseApi } from "@/config";
// create an axios instance
const service = axios.create({
  baseURL: baseApi, // url = base api url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// request 拦截器 request interceptor
service.interceptors.request.use(
  (config) => {
    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      Toast.loading({
        forbidClick: true,
      });
    }
    if (store.getters.token) {
      config.headers["X-Token"] = "";
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);
// respone拦截器
service.interceptors.response.use(
  (response) => {
    Toast.clear();
    const res = response.data;
    if (res.status && res.status !== 200) {
      // 登录超时,重新登录
      if (res.status === 401) {
        store.dispatch("FedLogOut").then(() => {
          location.reload();
        });
      }
      return Promise.reject(res || "error");
    } else {
      return Promise.resolve(res);
    }
  },
  (error) => {
    Toast.clear();
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);
export default service;

接口管理

src/api 文件夹下统一管理接口

javascript
import qs from "qs";
// axios
import request from "@/utils/request";
//user api

// 用户信息
export function getUserInfo(params) {
  return request({
    url: "/user/userinfo",
    method: "post",
    data: qs.stringify(params),
    hideloading: true, // 隐藏 loading 组件
  });
}

如何调用

javascript
// 请求接口
import { getUserInfo } from "@/api/user.js";

const params = { user: "sunnie" };
getUserInfo(params)
  .then(() => {})
  .catch(() => {});
`,10),e=[p];function t(c,r,F,y,D,i){return n(),a("div",null,e)}const u=s(o,[["render",t]]);export{C as __pageData,u as default};