基于vue axios二次封装的se-axios

介绍

se-axios是一个基于vue,axios进行二次封装的工具,开发者只需要使用提供的默认请求实例或者自定义请求实例即可发起请求,无需对请求参数以及响应数据进行拦截处理,se-axios已经帮开发者完成这部分工作
由于se-axios提供的拦截器使用了element-ui的组件,所以se-axios内置了element-ui,暂不支持非vue2项目使用

安装

npm install se-axios

特性

开发者只需要关注自己的项目请求方法

export function functionName(data){
    return request({
        url: '***/***',
        method: 'post',
        data: data
    })
}

提供了默认的请求拦截器,响应拦截器,满足大部分开发需求,开发者无需自己编写

开发者不满足默认的请求拦截器和响应拦截器时,可通过配置requestInterceptors和responseInterceptors来自定义自己的拦截器

{
   requestInterceptors: (config) =>{
        //....... 自己的请求拦截器逻辑
        //最后一定要return config
        return config
    },
    responseInterceptors:(res) =>{
        //....... 自己的响应拦截器逻辑
        return res.data
    }
}

提供了默认的请求实例,用户可以通过导入service直接使用,默认请求实例的baseURL:http://localhost:8080/

import { service } from "se-axios"
export function functionName(data){
    return service({
        url: '***/***/***',
        method: 'post',
        data: data,
    })
}

提供了自定义创建请求实例的接口,通过导入Request来创建自定义实例

import { Request } from "se-axios"
//使用自定义请求实例
const request = new Request({
    requestConfig:{
        baseURL: 'http://localhost:8080/***/',
        timeout: 2000,
    },
})

提供了函数来对响应数据进行处理,提示请求结果

开发者可以根据自己的需求自定义响应数据处理方式

const request = new Request({
    requestConfig:{
        baseURL: 'http://localhost:8080/***/',
        timeout: 2000,
        //在请求实例设置该函数对所有的请求都使用, 且方法名必须是success,warning,exception,		   //acquiesce
        success: (e) =>{ 
            console.log(e)
        },
        warning: (e) =>{
            console.log(e)
        },
        exception: (e) =>{
            console.log(e)
        },
        acquiesce: (e) =>{
            console.log(e)
        }
    },
})

//在具体的每个业务函数中定义时只对该函数有效
export function joinChat(data){
     return my({
        url: 'chat/login',
        method: 'post',
        data: data,
        success: (e) =>{
            Message({ message: e, type: 'success' })
        },
         exception: (e) =>{
             console.log('exception', e)
         }
    })
}

提供了setConfig和restoreConfig方法修改默认配置

import { setConfig, restoreConfig } from "se-axios"

//修改默认配置
setConfig({
    isToken: false
})
//还原默认配置
restoreConfig()

默认配置列表,可以根据实际需求通过setConfig添加自己的配置,通过导入requestConfig进行访问

{
    tokenName: 'token', //保存在浏览器的token
    responseTokenName: 'token', //后端返回的token
    index: '/login', //启用token时,当请求没有token或者token无效时跳转的页面
    isToken: true, //是否启用token
    headers:{ //请求头
            'Content-Type': 'application/json;charset=utf-8'
        },
    success: (e) =>{
    	Message({message: e, type: 'success'})
    },
    warning: (e)=>{
    	Message({message: e, type: 'warning'})
    },
    exception: (e) =>{
    	Message({message: e, type: 'error'})
    },
    acquiesce: (e) =>{
    	Message({message: e, type: 'info'})
    },
}

提供了错误码表,开发者可以根据实际进行修改添加

'warning': {
      401: {
        text: '401警告',
        type: null,
        default: 'warning'
      },
      403: {
        text: '403警告',
        type: null,
        default: 'warning'
      },
      404: {
        text: '404警告',
        type: null,
        default: 'warning'
      },
  },
    'exception': {
      500: {
        text: '500异常',
        type: null,
        default: 'error'
      },
      501: {
        text: '501异常',
        type: null,
        default: 'error'
      },
  },
  acquiesce: {
    text: '系统未知错误,请反馈给开发者',
    default: 'info'
  }

使用方法

  1. 在全局或局部导入se-axios

  2. 在需要请求的地方使用service或者自定义请求实例发送请求

    import { Request, service} from "se-axios"
    //创建自定义请求实例
    const request = new Request({
        requestConfig:{
            baseURL: 'http://localhost:8085/api/',
            timeout: 2000,
        },
    })
    export function joinChat(data){
        //在自己的函数中使用实例
        return request({
            url: 'chat/testpost',
            method: 'post',
            data: data
        })
    }
    
    //使用默认请求实例
    export function joinChat(data){
        return service({
            url: 'api/chat/login',
            method: 'post',
            data: data,
            exception:(e) =>{
                console.log('异常',e);
            }
        })
    }
    
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue 是一个前端框架,而 axios 是一个基于 Promise 的 HTTP 请求库。在 Vue 项目中,我们通常需要使用 axios 来进行接口请求。由于每个项目的接口返回数据结构和请求方式可能不同,因此我们需要对 axios 进行二次封装以方便统一管理。 二次封装可以解决以下问题: 1. 统一处理请求错误,例如网络错误、接口返回的错误码等。 2. 统一处理请求 loading 状态,避免每个请求都需要手动设置 loading 状态。 3. 统一处理请求头和请求参数等信息,避免每个请求都需要手动设置。 以下是一个简单的 vue axios 二次封装的示例: ``` // api.js import axios from 'axios' import { Message } from 'element-ui' const service = axios.create({ baseURL: process.env.VUE_APP_BASE_API, timeout: 5000 // 请求超时时间 }) // 请求拦截器 service.interceptors.request.use( config => { // 在这里可以统一设置请求头等信息 return config }, error => { // 请求错误时的处理 return Promise.reject(error) } ) // 响应拦截器 service.interceptors.response.use( response => { const res = response.data // 在这里可以统一处理接口返回的错误码等信息 if (res.code !== 0) { Message({ message: res.message || 'Error', type: 'error', duration: 5 * 1000 }) return Promise.reject(new Error(res.message || 'Error')) } else { return res } }, error => { // 响应错误时的处理 return Promise.reject(error) } ) export default service ``` 上述代码中,我们通过 axios.create 创建了一个 axios 实例,并对其进行了配置。在请求拦截器中,我们可以统一设置请求头等信息。在响应拦截器中,我们可以统一处理接口返回的错误码等信息,并使用 element-ui 中的 Message 组件来显示错误信息。 使用示例: ``` import request from '@/utils/api' request({ url: '/user/info', method: 'get', params: { id: 123 } }).then(response => { console.log(response) }).catch(error => { console.log(error) }) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值