当前位置:   article > 正文

【无标题】axios的ts封装,记录一下(Vue3项目)

【无标题】axios的ts封装,记录一下(Vue3项目)

request.ts:

// 参考:https://www.jb51.net/article/282238.htm
import axios from 'axios'

const instance = axios.create({
    baseURL: 'https://api.apiopen.top/api'
})

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    console.log('response', response)
    return response;
}, function (error) {
    // 服务器状态码不是200的情况
    // 对响应错误做点什么
    return Promise.reject(error);
});

export default instance
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

http.ts

import {AxiosResponse} from 'axios'
import instance from './request'
import QS from 'qs'
// 后端传来的数据格式
type Data<T> = {
    code: number,
    message: string,
    result: T
}

export function get<T>(url: string, params: object) {
    return instance.get<Data<T>, AxiosResponse<Data<T>>>(url, {
        params
    })
}

export function post<T>(url: string, data: object) {
    return instance.post<Data<T>, AxiosResponse<Data<T>>>(url, QS.stringify(data))
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/467921
推荐阅读