vue 请求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

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

{
    
    
  // 接口请求路径
  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) {
    
    
  })
}

完整的代码文件

https.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}`
  })
}

おすすめ

転載: blog.csdn.net/weixin_43876684/article/details/86318624