Vue axios的封装与使用

1.首先呈上axios的文档

Axios API | Axios 中文文档 | Axios 中文网 (axios-http.cn)

2:封装一个axios提供全局调用

封装一个axios
 /****   request.js   ****/
// 导入axios
import axios from 'axios'
axios.defaults.withCredentials = true;
// 使用element-ui Message做消息提醒
import { Message,MessageBox } from 'element-ui';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

//import global_ from '../components/Global'     //引用文件
//1. 创建新的axios实例,
const service = axios.create({
  // 公共接口--这里注意后面会讲
  baseURL: process.env.BASE_URL,
  // 超时时间 单位是ms,这里设置了3s的超时时间
  timeout: 300 * 1000
})
// 2.请求拦截器
service.interceptors.request.use(config => {
  //发请求前做的一些处理,数据转化,配置请求头,设置token,设置loading等,根据需求去添加
  // config.data = JSON.stringify(config.data); //数据转化,也可以使用qs转换
  // config.headers = {
  //     'Content-Type':'application/x-www-form-urlencoded' //配置请求头
  // }
  //注意使用token的时候需要引入cookie方法或者用本地localStorage等方法,推荐js-cookie
  // const token = getCookie('名称');//这里取token之前,你肯定需要先拿到token,存一下
  // if(token){
  //     config.params = {'token':token} //如果要求携带在参数中
  //     config.headers.token= token; //如果要求携带在请求头中
  // }
  return config
}, error => {
  Promise.reject(error)
})

// 3.响应拦截器
service.interceptors.response.use(response => {
  //接收到响应数据并成功后的一些共有的处理,关闭loading等
  var res = response;
  if (response.data.code == 200 || response.data.Code == 200) { //服务器返回成功
    return res.data;
  }
  else if (response.data.code || response.data.Code) {
    //服务端代码返回错误
    if (process.env.NODE_ENV.toUpperCase() == 'PRODUCTION' && (response.data.code == 403 || response.data.Code == 403)) {
      //鉴权失败自动跳转
      var LOGIN_URL = window.location.host;
      if (LOGIN_URL.indexOf(':') != -1) {
        LOGIN_URL = LOGIN_URL.substr(0, LOGIN_URL.indexOf(':'));
      }
      LOGIN_URL = 'http://' + LOGIN_URL + '/login';
      setTimeout(function () {//自动跳转回首页
        window.top.location.href = LOGIN_URL;
      }, 5000);
      MessageBox.confirm('登录超时,请重新登录!', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.top.location.href = LOGIN_URL;
      }).catch(() => {
        window.top.location.href = LOGIN_URL;
      });
    }
    //非鉴权失败返回错误信息
    return Promise.reject(response.data.msg ? response.data.msg : response.data.Msg)
  } else {
    return Promise.reject("接口未使用规范格式");
  }
  //return response
}, error => {

  /***** 接收到异常响应的处理开始 *****/
  if (error && error.response) {
    // 1.服务器抛出异常,根据响应码具体处理
    switch (error.response.status) {
      case 400:
        error.message = '请求失败'
        break;
      case 401:
        error.message = '未授权,请重新登录'
        break;
      case 403:
        error.message = '拒绝访问'
        break;
      case 404:
        error.message = '请求错误,请求功能不存在'
        break;
      case 405:
        error.message = '请求方法未允许,请检查Get/Post'
        break;
      case 408:
        error.message = '请求超时'
        break;
      case 500:
        error.message = '服务器端出错'
        break;
      case 501:
        error.message = '网络未实现'
        break;
      case 502:
        error.message = '网络错误'
        break;
      case 503:
        error.message = '服务不可用'
        break;
      case 504:
        error.message = '网络超时'
        break;
      case 505:
        error.message = 'http版本不支持该请求'
        break;
      default:
        error.message = `连接错误,${error.response.status}`
    }
    return Promise.reject(error.message)
  } else {
    // 浏览器抛出异常
    return Promise.reject('服务器响应超时,请刷新当前页')
  }
  /***** 处理结束 *****/
})
//4.导入文件
export default service

3:使用

使用
 
// 导入封装好的axios实例
import request from '../utils/request'
import axios from 'axios';

axios.defaults.withCredentials = true;

/**
 * 查询所有的组别绑定列表
 * @param {页面查询条件的json串} JsonStr
 * @param {当前页} page
 * @param {查询几条} rows
 * @returns
 */
export function GetRecordList(JsonStr, page, rows) {
  return request({
    url: '/FunctionCheck/GetRecordList',
    method: 'post',
    params: {JsonStr, page, rows}
  })
}

export function Edit(JsonStr) {
  return request({
    url: '/FunctionCheck/Edit?id='+JsonStr,
    method: 'get',
  })
}
export function Save(JsonStr) {
  return request({
    url: '/FunctionCheck/Save',
    method: 'post',
    params: {JsonStr}
  })
}
export function Delete(JsonStr) {
  return request({
    url: '/FunctionCheck/Delete',
    method: 'post',
    params: {JsonStr}
  })
}

 4:一些配置

{
  // `url` 是用于请求的服务器 URL
  url: '/user',

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

  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` 允许在向服务器发送前,修改请求数据
  // 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  // 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
  // 你可以修改请求头。
  transformRequest: [function (data, headers) {
    // 对发送的 data 进行任意转换处理

    return data;
  }],

  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  transformResponse: [function (data) {
    // 对接收的 data 进行任意转换处理

    return data;
  }],

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

  // `params` 是与请求一起发送的 URL 参数
  // 必须是一个简单对象或 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', 'DELETE 和 'PATCH' 请求方法
  // 在没有设置 `transformRequest` 时,则必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器专属: FormData, File, Blob
  // - Node 专属: Stream, Buffer
  data: {
    firstName: 'Fred'
  },
  
  // 发送请求体数据的可选语法
  // 请求方式 post
  // 只有 value 会被发送,key 则不会
  data: 'Country=Brasil&City=Belo Horizonte',

  // `timeout` 指定请求超时的毫秒数。
  // 如果请求时间超过 `timeout` 的值,则请求会被中断
  timeout: 1000, // 默认值是 `0` (永不超时)

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

  // `adapter` 允许自定义处理请求,这使测试更加容易。
  // 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
  adapter: function (config) {
    /* ... */
  },

  // `auth` HTTP Basic Auth
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` 表示浏览器将要响应的数据类型
  // 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
  // 浏览器专属:'blob'
  responseType: 'json', // 默认值

  // `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
  // 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // 默认值

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

  // `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
  xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值

  // `onUploadProgress` 允许为上传处理进度事件
  // 浏览器专属
  onUploadProgress: function (progressEvent) {
    // 处理原生进度事件
  },

  // `onDownloadProgress` 允许为下载处理进度事件
  // 浏览器专属
  onDownloadProgress: function (progressEvent) {
    // 处理原生进度事件
  },

  // `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
  maxContentLength: 2000,

  // `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
  maxBodyLength: 2000,

  // `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
  // 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
  // 则promise 将会 resolved,否则是 rejected。
  validateStatus: function (status) {
    return status >= 200 && status < 300; // 默认值
  },

  // `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
  // 如果设置为0,则不会进行重定向
  maxRedirects: 5, // 默认值

  // `socketPath` 定义了在node.js中使用的UNIX套接字。
  // e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
  // 只能指定 `socketPath` 或 `proxy` 。
  // 若都指定,这使用 `socketPath` 。
  socketPath: null, // 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` 定义了代理服务器的主机名,端口和协议。
  // 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
  // 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
  // `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
  // 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
  // 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // see https://axios-http.com/zh/docs/cancellation
  cancelToken: new CancelToken(function (cancel) {
  }),

  // `decompress` indicates whether or not the response body should be decompressed 
  // automatically. If set to `true` will also remove the 'content-encoding' header 
  // from the responses objects of all decompressed responses
  // - Node only (XHR cannot turn off decompression)
  decompress: true // 默认值

}
posted @ 2023-05-08 16:18  三五八团楚云飞  阅读(14)  评论(0)    收藏  举报