AXIOS二次封装

767 阅读4分钟

Axios基础知识

axios基本请求方法

通用方法 axios(config)
//GET
axios({
  method: 'get',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

/*-----*/

//POST
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

简写GET

axios.get(url[, config])
axios.get('http://localhost:9999/user/login').then((res) => {
    console.log(res)
})

简写POST

axios.post(url[, data[, config]])
axios.post('http://localhost:9999/user/login',{
    account:123,
    password:123
}).then((res) => {
    console.log(res)
})

创建一个新的Axios实例

//一般用来创建一个新配置项
axios.create([config])

分析配置项 config

{
   // `url` 是用于请求的服务器 URL
  url: '/user',
  // `method` 是创建请求时使用的方法
  method: 'get', // default
  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` 允许在向服务器发送前,修改请求数据
  // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
  transformRequest: [function (data, headers) {
    // 对 data 进行任意转换处理
    return data;
  }],

  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理
      /*
      	@1 比如后端需要 application/x-www-form-urlencoded 格式的数据
      	return qs.stringify(data)	//纯粹对象 => account=123&password=123
      */
    return data;
  }],

  // `headers` 是即将被发送的自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` 是即将与请求一起发送的 URL 参数
  // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  params: {
    ID: 12345
  },

   // `paramsSerializer` 是一个负责 `params` 序列化的函数
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` 是作为请求主体被发送的数据
  // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
  // 在没有设置 `transformRequest` 时,必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器专属:FormData, File, Blob
  // - Node 专属: Stream		默认传输的格式是application/json
  data: {
    firstName: 'Fred'
  },

  // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
  // 如果请求话费了超过 `timeout` 的时间,请求将被中断
  timeout: 1000,

   // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false, // default

  // `adapter` 允许自定义处理请求,以使测试更轻松
  // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
  adapter: function (config) {
    /* ... */
  },

 // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
  // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

   // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default

  // `responseEncoding` indicates encoding to use for decoding responses
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

   // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

   // `onUploadProgress` 允许为上传处理进度事件
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress` 允许为下载处理进度事件
  onDownloadProgress: function (progressEvent) {
    // 对原生进度事件的处理
  },

   // `maxContentLength` 定义允许的响应内容的最大尺寸 一般也不动
  maxContentLength: 2000,

  // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
  // 如果设置为0,将不会 follow 任何重定向
  maxRedirects: 5, // default

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default

  // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
  // `keepAlive` 默认没有启用
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' 定义代理服务器的主机名称和端口
  // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
  // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` 指定用于取消请求的 cancel token
  // (查看后面的 Cancellation 这节了解更多)
  cancelToken: new CancelToken(function (cancel) {
  })
}

全局的 axios 默认值

使用defaults

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

image-20210528161310890

自定义实例默认值

// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

拦截器

返回一个Promise

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

//移除拦截器
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

axios二次封装

http.js

/* 
  axios二次封装:把每一次基于axios发送请求的公共部分进行提取
    + axios.defaults.xxx
    + axios.interceptors.request/response  拦截器 
 */
import axios from 'axios';
import qs from 'qs';
import tool from './tool';

// 请求URL地址没有加前缀,则默认把BASE-URL加上;如果请求时候,自己设置前缀了,则以自己写的为主;
// 真实开发的时候,我们项目有各种不同的环境「开发、测试、灰度、生产」:我们需要针对不同的环境,有不同的BASE-URL
//  1)在运行编译的时候,设置环境变量
//    + 安装cross-env插件   $ npm i cross-env
//    + package.json的scripts中做处理
//      开发环境 serve:"cross-env NODE_ENV=development vue-cli-service serve",
//      生产环境 build:"cross-env NODE_ENV=production vue-cli-service build"
//  2)在代码中获取环境变量的值,根据不同值,设置不同的BASE-URL
let env = process.env.NODE_ENV || 'development',
    baseURL = '';
switch (env) {
    case 'development':
        baseURL = 'http://127.0.0.1:9999';
        break;
    case 'production':
        baseURL = 'http://api.zhufengpeixun.cn';
        break;
}
axios.defaults.baseURL = baseURL;

// 一些可以提取的小东西:超时时间 & CORS跨域中是否允许携带资源凭证(例如:cookie)
//   + 客户端的withCredentials:true,那么服务器端也要设置为允许
axios.defaults.timeout = 10000;
axios.defaults.withCredentials = true;

// POST系列请求中:请求主体中传递给服务器的信息,项目要求需要是URLENCODED格式;当代浏览器中,我们请求主体传递给服务器的格式是啥,浏览器会自动在请求头中,更新Content-Type!
axios.defaults.transformRequest = data => {
    // 只有我们写的DATA是一个纯粹的对象,才需要按需求处理
    if (tool.isPlainObject(data)) data = qs.stringify(data);
    return data;
};

// 自己规定,服务器返回的状态码,值是多少算是请求成功
//   成功:服务器正常返回响应信息,且返回的HTTP状态码是经过validateStatus校验通过的
//   失败:
//   + 服务器有返回的信息,但是返回的HTTP状态码并没有经过validateStatus的校验
//   + 请求超时或者请求中断  reason.code==='ECONNABORTED'
//   + 服务器没有返回任何信息「可能是断网了」
//   + ...
axios.defaults.validateStatus = status => {
    return status >= 200 && status < 400;
};

// 请求拦截器:在axios内部已经把config的那些配置项处理差不多了,并且打算按照配置项,向服务器发送请求之前进行拦截;拦截目的是把配置项中的一些信息再改改!
axios.interceptors.request.use(config => {
    // 常见需求:在每一次发送请求的时候,通过请求头把token信息传递给服务器
    const token = localStorage.getItem('token');
    if (token) {
        config.headers['Authorization'] = token;
    }
    return config;
});

// 响应拦截器:onfulfilled/onrejected,发生在请求成功/失败,在业务层具体.then/catch之前进行拦截处理
axios.interceptors.response.use(response => {
    // 请求成功:一般我们会返回响应主体信息
    return response.data;
}, reason => {
    // 请求失败:一般我们会做统一的错误提示
    if (reason && reason.response) {
        let response = reason.response;
        // 有响应信息,但是状态码不对,我们根据不同的状态码做不同的提示
        switch (response.status) {
            case 400:
                // ...
                break;
            case 401:
                // ...
                break;
            case 404:
                // ...
                break;
        }
    } else {
        if (reason && reason.code === 'ECONNABORTED') {
            // 请求超时或者中断
        }
        if (!navigator.onLine) {
            // 断网了
        }
    }
    return Promise.reject(reason);
});

export default axios;

index.js 入口文件

import axios from './http';
import instance from './http2';
import md5 from 'blueimp-md5';

const queryUserList = (departmentId = 0, search = '') => {
    return axios.get('/user/list', {
        params: {
            departmentId,
            search
        }
    });
};

const setUserLogin = (account, password) => {
    password = md5(password);
    return axios.post('/user/login', {
        account,
        password
    });
};

export default {
    queryUserList,
    setUserLogin
};

vue 中挂载到全局 在main.js中

import Vue from 'vue';
import App from './App.vue';
import api from './api/index';

Vue.config.productionTip = false;

//之后每个页面this.$api可以获取
Vue.prototype.$api = api;

new Vue({
  render: h => h(App),
}).$mount('#app');