axios封装的请求及拦截统一管理,和之前相比方便添加自定义请求头和超时

1、api.js文件

import axios from 'axios'
import { Message } from 'element-ui'

const timeout = 5000 // 默认超时

const api = axios.create({
 baseURL: '', // 设置API的基础URL
 timeout: timeout, // 设置超时时间,单位为毫秒
 headers: {
  'Content-Type': 'application/json', // 设置通用的请求头
 },
})

// 请求拦截
api.interceptors.request.use(
 config => {
  return config
 },
 err => {
  return err
 }
)

// 响应拦截
api.interceptors.response.use(
 response => {
  if (response.data.code == 200) return response.data.data
  Message({
   type: 'warning',
   showClose: true,
   duration: 1200,
   message: response.data.msg,
  })
  return Promise.reject(response.data.msg)
 },
 err => {
  // 添加超时处理级响应错误
  if (err.code == 'ECONNABORTED') {
   Message.error('请求超时,请重新尝试')
  } else {
   // 添加404和500
   switch (err.response.status) {
    case 400:
     Message.error('参数有误')
     break
    case 404:
     Message.error('服务器中查找不到该资源')
     break
    case 500:
     Message.error('请求失败,服务端错误,请重新尝试')
     break
   }
  }
  return Promise.reject(err)
 }
)

const get = (url, params = {}, config = {}) => {
 return new Promise((resolve, reject) => {
  api
   .get(url, {
    params,
    ...config,
   })
   .then(res => {
    resolve(res)
   })
   .catch(e => {
    reject(e)
   })
 })
}

const post = (url, data = {}, config = {}) => {
 return new Promise((resolve, reject) => {
  api
   .post(url, data, config)
   .then(res => {
    resolve(res)
   })
   .catch(e => {
    reject(e)
   })
 })
}

export { get, post }

2、index.js

import { get, post } from './axios'
import store from '../store'

// 本文件里(post同理):
 export const test_get_api = (params, config) =>
  get("http://127.0.0.1:8081/api/test_api", params, config)

// .vue界面中
test_get_api({ name: '管理员' }, { headers: { Test: 'test_headers' }, timeout: 1000 })
 .then(res => {
  console.log(res)
 })
 .catch(e => {
  console.log(e)
 })

 

posted @ 2023-07-18 16:49  yw3692582  阅读(97)  评论(0编辑  收藏  举报