简介

在开发中,网络请求是不可或缺的一部分。在之前的Vue2.0中官方推荐使用axios作为网络请求插件,取消对 vue-resource 的官方推荐。下面就介绍一下,我们在开发中axios的使用。

简单使用
GET请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
POST请求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
多并发请求
function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));

掌握了这些,就已经可以实现我们在开发中的网络请求实现了。但是,在开发中,我们通常会遇见需要结合当前的项目需求、业务逻辑等,提供一个易扩展,方便统一处理的接口。
接下来,我们就对axios进行封装。

封装axios

在我们的开发中,通常都会要求在网络请求前或网络请求后作出相应的处理。这时候,我们就要考虑两个问题:

  • 配置网络请求的通用项
  • 对接口请求失败、异常的统一处理
配置网络请求的通用项

我们通常会遇到一些业务:例如 接口请求的超时时间、header等。在axios中,提供了request拦截器.我们在对应的回调函数中根据相应的业务做处理即可。

import axios from 'axios'

axios.interceptors.request.use((config) => {
 // 接口请求可在此处统一处理
  return config
}, (err) => {
  // 接口请求出错可在此处统一处理
  return Promise.resolve(err)
})
对接口请求失败、异常的统一处理

在开发中,我们都不知道确定网络请求的结果。请求成功,需要我们做处理。请求失败,也会需要有相应的处理。

axios.interceptors.response.use((data) => {
  // 数据统一校验处理
  return data
}, (err) => {
   // 数据异常统一处理 例如
  if (err.response.status === 504 || err.response.status === 404) {
    alert('服务器被吃了')
  } else if (err.response.status === 403) {
    alert('权限不足,请联系管理员')
  } else {
    alert('未知错误')
  }
  return Promise.resolve(err)
})
封装axios

axios中提供了各种参数配置,我们接下来就封装部分参数,用来我们开发的工具。

{
  // 接口请求路径
  url: '/user',

  // 接口请求方式,默认为get
  method: 'get', // default

  // 当url不是绝对路径的时候,会将此参数拼接在url之前。 默认空
  baseURL: 'https://some-domain.com/api/',

  // 提前处理接口请求参数 支持 POST PUT  PATCH
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],

  // 预先处理请求结果 
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

  // 自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},

 // 请求参数
  params: {
    ID: 12345
  },

  // 请求参数序列化 可选
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },
 // 上传数据
   data: {
    firstName: 'Fred'
  },

  // 超时时间
  timeout: 1000,

  // 证书验证
    withCredentials: false, // default

  // `adapter` allows custom handling of requests which makes testing easier.
  // Return a promise and supply a valid response (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // 支持授权验证 如jira等
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // 接口请求返回接口类型
  responseType: 'json', // default

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

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

  // 上传进度
  // `onUploadProgress` allows handling of progress events for uploads
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },
  //下载进度
  // `onDownloadProgress` allows handling of progress events for downloads
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `maxContentLength` defines the max size of the http response content allowed
  maxContentLength: 2000,

  // `validateStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  maxRedirects: 5, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' defines the hostname and port of the proxy server
  // Use `false` to disable proxies, ignoring environment variables.
  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  // supplies credentials.
  // This will set an `Proxy-Authorization` header, overwriting any existing
  // `Proxy-Authorization` custom headers you have set using `headers`.
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies a cancel token that can be used to cancel the request
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  })
}
POST
export function postRequest(url, params) {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}
GET
export function getRequest(url) {
  return axios({
    method: 'get',
    url: `${base}${url}`
  })
}
uploadFile
export function uploadFileRequest(url, params) {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}
PUT
export function putRequest(url, params) {
  return axios({
    method: 'put',
    url: `${base}${url}`,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}
delete
export function deleteRequest(url) {
  return axios({
    method: 'delete',
    url: `${base}${url}`
  })
}

封装之后,就一目了然。接口请求有了统一的入口和出口。方便我们统一管理接口请求。

使用示例

我们在main.js中将常用的接口请求挂在到vue上,方便使用。

import {postRequest, getRequest} from './common/js/request'
Vue.prototype.postRequest = postRequest
Vue.prototype.getRequest = getRequest

这里写图片描述

接口调用

挂在到vue上后,我们可以直接使用this访问到我们的定义的接口请求。

      //post请求
      this.postRequest('post', {
          username: 'lvcq',
          password: '123456'
      }).then((res) => {
          console.log(res)
      })
      //get请求
    this.getRequest(`get?name=lvcq&password=12312`).then((res) => {
          console.log(res)
    })

这里写图片描述

最后,完整的代码文件

request.js文件代码

/**
 * Created by BruceLv on 2018/1/22.
 */
import axios from 'axios'

let base = 'https://httpbin.org/'

axios.interceptors.request.use((config) => {
  return config
}, (err) => {
  alert('请求超时')
  return Promise.resolve(err)
})


axios.interceptors.response.use((data) => {
  // 数据统一校验处理
  return data
}, (err) => {
   // 数据异常统一处理
  if (err.response.status === 504 || err.response.status === 404) {
    alert('服务器被吃了')
  } else if (err.response.status === 403) {
    alert('权限不足,请联系管理员')
  } else {
    alert('未知错误')
  }
  return Promise.resolve(err)
})


export function postRequest(url, params) {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

export function uploadFileRequest(url, params) {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

export function putRequest(url, params) {
  return axios({
    method: 'put',
    url: `${base}${url}`,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

export function deleteRequest(url) {
  return axios({
    method: 'delete',
    url: `${base}${url}`
  })
}

export function getRequest(url) {
  return axios({
    method: 'get',
    url: `${base}${url}`
  })
}
Logo

前往低代码交流专区

更多推荐