vue封装request

 request.ts  
目录中位置  vue封装request_第1张图片

import axios from 'axios'
import store from '@/store'
import { ElMessage } from 'element-plus'
const baseURL = import.meta.env.VITE_BASE_URL

const service = axios.create({
  baseURL: baseURL,
  timeout: 5000
})

// 请求前的统一处理
service.interceptors.request.use(
  (config) => {
    // JWT鉴权处理
    if (store.getters['user/token']) {
      config.headers['token'] = store.state.user.token
    }
    return config
  },
  (error) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code === 200) {
      return res
    } else {
      showError(res)
      return Promise.reject(res)
    }
  },
  (error)=> {
    console.log(error) // for debug
    const badMessage = error.message || error
    const code = parseInt(badMessage.toString().replace('Error: Request failed with status code ', ''))
    showError({ code, message: badMessage })
    return Promise.reject(error)
  }
)

function showError(error) {
  if (error.code === 403) {
    // to re-login
    store.dispatch('user/loginOut')
  } else {
    ElMessage({
      message: error.msg || error.message || '服务异常',
      type: 'error',
      duration: 3 * 1000
    })
  }
  
}

export default service

api设置引入 传入接口参数方法
 

import request from '@/utils/system/request'

// 获取数据api
export function getData(data: object) {
  return request({
    url: '/card/list',
    method: 'post',
    baseURL: '/mock',
    data
  })
}

页面组件中调用getData方法

      getData(params)
      .then(res => {
        page.total = res.data.pager.total
        list.value = res.data.list
      })
      .catch(err => {
        list.value = []
        page.index = 1
        page.total = 0
      })
      .finally(() => {
        loading.value = false
      })
    }

你可能感兴趣的:(javascript,前端,vue.js)