vue3+vite 封装axios请求

简介: vue3+vite 封装axios请求

安装axios

npm install axios

创建axios实例

// http/index.js
import axios from 'axios'
import {
    ElLoading,
    ElMessage
} from 'element-plus';
//创建axios的一个实例 
var instance = axios.create({
    baseURL: import.meta.env.VITE_APP_URL, //接口统一域名
    timeout: 6000, //设置超时
    headers: {
        'Content-Type': 'application/json;charset=UTF-8;',
    }
})
let loading;
//正在请求的数量
let requestCount = 0
//显示loading
const showLoading = () => {
    if (requestCount === 0 && !loading) {
        loading = ElLoading.service({
            text: "Loading  ",
            background: 'rgba(0, 0, 0, 0.7)',
            spinner: 'el-icon-loading',
        })
    }
    requestCount++;
}
//隐藏loading
const hideLoading = () => {
    requestCount--
    if (requestCount == 0) {
        loading.close()
    }
}
//请求拦截器 
instance.interceptors.request.use((config) => {
        showLoading()
        // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
        const token = window.localStorage.getItem('token');
        token && (config.headers.Authorization = token)
        //若请求方式为post,则将data参数转为JSON字符串
        if (config.method === 'POST') {
            config.data = JSON.stringify(config.data);
        }
        return config;
    }, (error) =>
    // 对请求错误做些什么
    Promise.reject(error));
//响应拦截器
instance.interceptors.response.use((response) => {
    hideLoading()
    //响应成功
    console.log('拦截器报错');
    return response.data;
}, (error) => {
    console.log(error)
    //响应错误
    if(error.response&&error.response.status){
     const status = error.response.status
      switch (status) {
          case 400:
              message = '请求错误';
              break;
          case 401:
              message = '请求错误';
              break;
          case 404:
              message = '请求地址出错';
              break;
          case 408:
              message = '请求超时';
              break;
          case 500:
              message = '服务器内部错误!';
              break;
          case 501:
              message = '服务未实现!';
              break;
          case 502:
              message = '网关错误!';
              break;
          case 503:
              message = '服务不可用!';
              break;
          case 504:
              message = '网关超时!';
              break;
          case 505:
              message = 'HTTP版本不受支持';
              break;
          default:
              message = '请求失败'
      }
        ElMessage.error(message);
        return Promise.reject(error);
       }
    return Promise.reject(error);
});
export default instance;

封装请求方式

// http/request.js
import instance from "./index"
/**
 * @param {String} method  请求的方法:get、post、delete、put
 * @param {String} url     请求的url:
 * @param {Object} data    请求的参数
 * @param {Object} config  请求的配置
 * @returns {Promise}     返回一个promise对象,其实就相当于axios请求数据的返回值
 */
const axios = ({
    method,
    url,
    data,
    config
}) => {
    method = method.toLowerCase();
    if (method == 'post') {
        return instance.post(url, data, {...config})
    } else if (method == 'get') {
        return instance.get(url, {
            params: data,
            ...config
        })
    } else if (method == 'delete') {
        return instance.delete(url, {
            params: data,
            ...config
        }, )
    } else if (method == 'put') {
        return instance.put(url, data,{...config})
    } else {
        console.error('未知的method' + method)
        return false
    }
}
export default axios

封装请求接口

创建api文件

import axios from "../http/request"
//请求示例
//get
export const mokeGet = (data) => {
    return axios({
        url: "/api/xxxx",
        method: "get",
        data,
        config: {
            headers: {
                'Request-Type': 'wechat'
            },
            timeout: 10000
        }
    })
}
//post
export const mokePost = (data) => {
    return axios({
        url: "/api/xxxx",
        method: "post",
        data,
        config: {
            headers: {
                'Request-Type': 'wechat'
            },
            timeout: 10000
        }
    })
}

vue中调用

import { mokePost } from "@/api";
import {onMounted} from "vue"
export default {
  setup() {
     onMounted(() => {
      mokePost().then(res=>{
        console.log(res)
      })
    })
    return {};
  },
};


相关文章
|
8天前
|
JavaScript
vue页面加载时同时请求两个接口
vue页面加载时同时请求两个接口
|
6天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
10 1
|
6天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
13 0
|
6天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
11 0
|
6天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
12 1
|
7天前
|
存储 缓存 JavaScript
如何从 Vue CLI 迁移到 Vite
如何从 Vue CLI 迁移到 Vite
|
7天前
|
JavaScript Go
VUE3+vite项目中动态引入组件和异步组件
VUE3+vite项目中动态引入组件和异步组件
|
8天前
|
JavaScript
axios拦截器:每次请求自动带上 token
axios拦截器:每次请求自动带上 token
11 0
|
8天前
|
前端开发 JavaScript 数据格式
vue3中axios添加请求和响应的拦截器
vue3中axios添加请求和响应的拦截器
17 1
|
8天前
|
缓存 前端开发 JavaScript
前端vue3分享——项目封装axios、vite使用env环境变量
前端vue3分享——项目封装axios、vite使用env环境变量
36 0