axios的使用和接口请求统一封装处理

axios的使用和接口请求统一封装处理_第1张图片

 axios官网:axios中文网|axios API 中文文档 | axios

简单封装:配置基础路径和超时时间,还有请求拦截器和响应拦截器 

//对axios进行二次封装
import axios from 'axios'

//1、利用axios对象的方法create,去创建一个axios实例
const requests = axios.create({
    //配置对象
    //基础路径,requests发出的请求在端口号后面会跟改baseURl
    baseURL: '/api',
    //代表请求超时的时间5s
    timeout: 5000,
})
//请求拦截器,在请求发出之前做些事情
requests.interceptors.request.use((config) => {
    //config:配置对象,对象里面有个属性很重要,header请求头
    return config
})
//响应拦截器,对响应的数据做一些操作
requests.interceptors.response.use(
    (res) => {
        //成功回调函数,服务器响应数据回来以后,响应拦截器可以检测到,可以做一些事情
        return res.data
    },
    (error) => {
        //响应失败回调函数,如终结Promise链
        console.log('请求失败:', error)
        return Promise.reject(error)
    }
)
//对外暴露
export default requests

 

接口统一管理 api/index.js

import requests from '@/utils/http'

export default {
    getList(data) {
        return requests({
            url: '/message/list',
            method: 'post',
            data,
        })
    },
    changeStatus(data) {
        return requests({
            url: '/message/isReads',
            method: 'post',
            data,
        })
    },
    getMsgType(params) {
        return requests({
            url: '/message/messageType',
            method: 'get',
            params,
        })
    },
    deleteMsg(data) {
        return requests({
            url: '/message/delete',
            method: 'post',
            data,
        })
    },
}

ts格式的请求:

import requests from '@/utils/http'

export default {
    getList(data: object) {
        return requests({
            url: '/message/list',
            method: 'post',
            data,
        })
    },
    changeStatus(data: object) {
        return requests({
            url: '/message/isReads',
            method: 'post',
            data,
        })
    },
    getMsgType(params: object) {
        return requests({
            url: '/message/messageType',
            method: 'get',
            params,
        })
    },
    deleteMsg(data: object) {
        return requests({
            url: '/message/delete',
            method: 'post',
            data,
        })
    },
}

在组件中使用get请求:

      try {
        const { data } = await msgApi.getMsgType()
        data && (this.msgTypelist = Object.keys(data).map((i) => {
          const obj = {}
          obj.id = +i
          obj.label = data[i]
          return obj
        }))
      } catch (error) {
        console.log(error)
      }

发送Post请求:

      msgApi.changeStatus({ ids: idArr }).then((res) => {
        if (res.retcode === 0) {
          this.$message.success('操作成功')
        }
      })

带有鉴权方案的axios封装:

import axios from 'axios'
// import store from '@/store'
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: `${window.location.origin}/fate-serving/api`,
  withCredentials: false,
  timeout: 20000 // request timeout
})
// request interceptor
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('sessionToken')
    config.headers['sessionToken'] = token
    return config
  },
  error => {
    // Do something with request error
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get information such as headers or status
   * Please return  response => response
   */
  response => {
    const res = response.data
    if ((res.code !== undefined && res.code === 0) || (res.retcode !== undefined && res.retcode === 0)) {
      return new Promise(resolve => {
        resolve(res)
      })
    } else if (res.code === 401) {
      Message({
        message: '登录已失效,请重新登录',
        type: 'warning',
        duration: 2 * 1000
      })
      localStorage.removeItem('sessionToken')
      // setTimeout(() => {
      //   window.location.reload()
      // }, 800)
    } else {
      Message({
        message: res.message || res.msg || res.retmsg,
        type: 'error',
        duration: 2 * 1000
      })
      return Promise.reject('error')
    }
  },
  error => {
    console.log('err:', error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

你可能感兴趣的:(HTML前端,javascript,前端,html)