利用Promise封装Axios

238 阅读2分钟

axios 简介

axios时目前最流行的ajax封装库之一,用于很方便地实现ajax请求的发送。

支持功能:

  1. 从浏览器发出 XMLHttpRequests请求
  2. 从 node.js 发出 http 请求
  3. 支持 Promise API
  4. 能拦截请求和响应
  5. 能转换请求和响应数据
  6. 实现JSON数据的自动转换

axios 使用详解

1.安装

npm install axios

2.使用

// 第一种写法
axios.get('/query?id=123')
  .then(function (response) 
    { console.log(response); 
   })
  .catch(function (error) 
    { console.log(error); 
});
//第二种写法
axios.get('/query', {
    params: {
        id: '123'
    }
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});
//第三种写法
axios({
  method: 'get',
  url: '/query',
  data: {
    id: '123',
  }
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

3.参数配置

axios({
  // 请求的服务器 URL
  url: '/user',

  // 创建请求时使用的方法
  method: 'get', // 默认是 get

  // 将自动加在 url 前
  baseURL: 'https://some-domain.com/api/',

  // 在向服务器发送前,修改请求数据
  // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
  transformRequest: [function (data) {
    // 对 data 进行任意转换处理
    return data;
  }],
  
  // 在传递给 then/catch 前,修改响应数据
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理
    return data;
  }],
  
  // 自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // 与请求一起发送的 URL 参数
  params: {
    ID: 12345
  },

  // 用于 params 的序列化的函数
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // 请求发送的数据,适用于 PUT, POST, 和 PATCH
  // 在没有设置 transformRequest 时,必须是以下类型之一:
  // string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // 浏览器专属:FormData, File, Blob
  // Node 专属: Stream
  data: {
    firstName: 'Fred'
  },

  // 指定请求超时毫秒数(0 表示无超时时间)
  timeout: 1000,

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

  // 允许自定义处理请求,常用用于测试
  adapter: function (config) {
    /* ... */
  },
  
  // 表示应该使用 HTTP 基础验证,并提供凭据,该参数会在 headers 设置 Authorization
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // 表示服务器响应的数据类型,
  // 支持类型:arraybuffer, blob, document, json(默认), text, stream
  responseType: 'json', 

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

  //  xsrf token 值的 HTTP 头的名称
  xsrfHeaderName: 'X-XSRF-TOKEN', 

  // 上传处理进度事件
  onUploadProgress: function (progressEvent) {
  },

  // 下载处理进度事件
  onDownloadProgress: function (progressEvent) {
  },

  // 响应内容的最大尺寸
  maxContentLength: 2000,
  
  // 定义对于给定的HTTP 响应状态码。
  validateStatus: function (status) {
    return status >= 200 && status < 300; 
  },

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

  // 在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' 定义代理服务器的主机名称和端口
  // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: : {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  }
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

利用promise二次封装axios

1.封装

import axios from 'axios'
import { Message } from 'element-ui'
import ref from '@/main'
import { baseApiUrl } from '../../static/js/config'
import { handleErrorTip } from '../../static/js/errorFunction'

const ajax = axios.create({
  baseURL: baseApiUrl,
  withCredentials: true
})

ajax.interceptors.request.use(
  config => {
    return config
  }
)

ajax.interceptors.response.use(response => {
  return response
}, error => {
  Message.error(`${error.message}`)
  return Promise.reject(error)
})

const handleResponse = ({config, data}) => {
  const {code, body} = data
  if (code === '200') {
    return Promise.resolve(body)
  } else {
    handleErrorTip(data, ref)
    return Promise.reject(data)
  }
}

const $get = function $get (url, params = {}, options = {}) {
  return ajax.get(url, {params, ...options})
    .then(handleResponse)
}
const $post = function $post (url, data, options = {}) {
  return ajax.post(url, data, options)
    .then(handleResponse)
}

export default ajax

export {$get, $post}

2.使用

//url:接口地址
//params:参数
//response:响应结果

//get请求
this.$get(url, params).then(response => {
  console.log(response);
});

//post请求
this.$post(url,params).then(response => {
  console.log(response);
});