axios封装

2022-07-29,

安装

npm install axios

代码

import axios from 'axios'
import Vue from 'vue'
// import qs from 'qs' // 如果要求 参数序列化

// export let ConfigBaseURL = 'http://*****' // 默认路径,这里也可以使用env来判断环境
export let ConfigBaseURL = 'http://******' // 测试

// 使用create方法创建axios实例
export const Service = axios.create({
  // timeout: 7000, // 请求超时时间
  baseURL: ConfigBaseURL,
  method: 'post' // 默认post
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 添加请求拦截器 一般是对参数请求头做处理
Service.interceptors.request.use(config => { // config 向后端传递的参数
  const token = localStorage.getItem('token')
   // 如果路径不是 '/', 参数里面没有token , 参数里面的 whiteList 是 true ,就给请求头拼接token
  if (config.publicPath !== '/' && token && !config.whiteList) { // whiteList 自定义的
    config.headers.Authorization = 'Bearer ' + localStorage.getItem('token')
  }
  // config.data && (config.data = qs.stringify(config.data)) // 参数序列化
  return config
})

// 添加响应拦截器  一般是对后端返回的code信息做处理
Service.interceptors.response.use(response => {
  const data = response.data
  // eslint-disable-next-line eqeqeq
  if (data.code && data.code != 200) { // 返回的code不是200
    const msg = data.descrp || data.msg
    Vue.toasted.show(msg, { // totip提示,返回msg错误原因
      duration: 2000,
      type: 'error'
    })
    if (data.code === 401 || data.code === 405) { // 返回规定的状态码,这里是token失效执行的操作
      localStorage.removeItem('token')
      this.$router.push('/phoneLogin')
    }
    return Promise.reject(new Error(msg || '系统出现错误'))
  } else {
    return data
  }
},
(error) => { // 这里是接口报错了但是有返回信息,模拟了下token失效
  if (error.response.data.code === 405) {
    localStorage.removeItem('token')
    this.$router.push('/phoneLogin')
  }
}
)

export default Service

  • api/index.js 调用
import Service from './axios'

// 首页资产 公告
export function index (data) {
  return Service({
    url: 'zh/walletindex', // 接口
    method: 'post',  // 请求方式
    data // 参数
  })
}

// 公告接口
export function detail (params) {
  return Service({
    url: 'zh/fil_usdt',
    method: 'get',
    whiteList: true, // 自定义的参数,
    params
  })
}

页面使用

import { index, detail } from 'src/api/index'

export default {
  data() {
    return {
    	indexData:{}
    	usdt:{}
    };
  },
  created () {
    this.initData()
  },
  methods: {
    async initData () {
      const res = await index({ page : 1 })
      this.indexData = res.data
    },
    async getdetail  () {
      const res = await detail({ params: { page: 1 } })
      this.usdt = res.data
    }
};

本文地址:https://blog.csdn.net/weixin_44955769/article/details/112561057

《axios封装.doc》

下载本文的Word格式文档,以方便收藏与打印。