工程化axios封装

  1. npm i axios -S下载axios
  2. 创建utils/request.js

代码分析

import axios from "axios"; //导入axios
import Qs from "qs"; //和后台约定好

const service = axios.create({
  baseURL: process.env.BASE_API, //
  timeout: 10000, //10s后告知用户超时,需要刷新界面
  transformRequest: [
    function(data) {
      // `transformRequest` 允许在向服务器发送前,修改请求数据
      // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
      return Qs.stringify(data);
      // 结合create_headers里的内容,在这里又新增一条信息例如当前是id=001
      // 因此network中查看的结果是:name=xiaoming&age=12&id=001
    }
  ],
  headers: { "Content-Type": "application/x-www-form-urlencoded" }
});

//请求拦截器
service.interceptors.request.use(
  config => {
    //和后台协定的必要参数
    config.headers["token"] = "111";
    config.headers["gid"] = "222";
    config.headers["from"] = "3";
    return config;
  },
  error => {
    console.log(error);
    Promise.reject(error);
  }
);

//响应拦截器
service.interceptors.response.use(
  response => {
    //接受到后台响应数据后做的操作,一般是关闭loading状态和直接返回
    const res = response.data;
    //如果成功响应
    if (res.status == 0) {
      return res;
    }
  },
  error => {
    //如果失败了
    Promise.reject(error);
  }
);

//根据接口的method来判断
const http = url => {
  if (url.method == "get") {
    //第一个参数表示我们要请求的url地址,第二个参数是我们要携带的请求参数
    return service.get(url.url, url.params);
  } else if (type == "post") {
    //post方法必须要使用对提交从参数对象进行序列化
    return service.get(url.url, { params: url.params });
  }
};
export default http;

3.创建api/api.js 封装所有的接口

import fetch from "../utils/request";
//暴露接口
export function getList(params) {
  return fetch({
    method: "get",
    url: "/api/activity/targets/get_detail",
    params
  });
}

4、界面引用

//先引入
import { getList } from "@/api/api";
...
 methods: {
    fetchData() {
       getList({ id: 111 }).then(
        res => {				console.log("成功后的代码")
			},

      ).catch(error=>{
				consolelog(error);
			});
    }
  },
  mounted:function(){
      this.fetchData();
  }

参考1: https://blog.csdn.net/weixin_43216105/article/details/98877960

参考2:公司项目

原文地址:https://www.cnblogs.com/hanhaiyuntao/p/14066893.html