vue中关于axios的简单封装,api集中管理, typescript

axios 简单封装

在项目开发中进行项目开发时,对api接口进行集中管理非常重要

由于之前没有怎么封装过,只知道一些简单使用,所以最近根据网上的一些教程试着写了一下

  1. 我在src目录下新建了一个叫api 的文件夹,文件夹里新建了2个ts文件,api.tshttp.ts,
    其中api.ts 用来集中管理后端接口http.ts用来对axios进行封装

  2. 在http.ts中对axios代码进行如下封装(下面是http.ts的完整代码)

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import qs from 'qs'

/**
 * @auther boyyang-love 
 * @NODE_ENV 根据当前环境确定请求地址
 * @development 开发环境、
 * @production 生产环境
 * @debug  测试环境
 */

const server: AxiosInstance = axios.create({
    baseURL: process.env.NODE_ENV == 'development' ? 'http://1905.com': 'http://2020.com' ,
    timeout: 3000,
})

/**
 * axios请求拦截
 * @return 
 * @config
 */
server.interceptors.request.use(
    (config: AxiosRequestConfig): AxiosRequestConfig | Promise<AxiosRequestConfig> => {
        if (config.method == 'get') {
            config.headers.get['Content-Type'] =  'application/x-www-form-urlencoded;charset=utf-8' 
        }
        if (config.method == 'post') {
            config.headers.post['Content-Type'] =  'application/json;charset=utf-8' 
        }
        // const token = '1111111';        
        // token && (config.headers.Authorization = token);
        console.log(config)
        return config;
    },
    (error) => {
        return Promise.reject(error)
    }
)
/**
 * 响应拦截
 * @return 
 * @response
 */

server.interceptors.response.use(
    (response: AxiosResponse<any>): AxiosResponse<any> | Promise<AxiosResponse<any>> => {
        return response
    },
    error => {
        if (error && error.response) {
            switch (error.response.status) {
                case 400:
                    console.log('错误请求')
                    break;
                case 401:
                    console.log('未授权,请重新登录')
                    break;
                case 403:
                    console.log('拒绝访问')
                    break;
                case 404:
                    console.log('请求错误,未找到该资源')
                    break;
                case 405:
                    console.log('请求方法未允许')
                    break;
                case 408:
                    console.log('请求超时')
                    break;
                case 500:
                    console.log('服务器端出错')
                    break;
                case 501:
                    console.log('网络未实现')
                    break;
                case 502:
                    console.log('网络错误')
                    break;
                case 503:
                    console.log('服务不可用')
                    break;
                case 504:
                    console.log('网络超时')
                    break;
                case 505:
                    console.log('http版本不支持该请求')
                    break;
                default:
                    console.log(`连接错误${error.response.status}`)
            }
        } else {
            console.log('服务未连接')
        }
        return Promise.resolve(error.response)
    }
)

/**
 * 导出get请求方法
 * @url 请求地址
 * @params get请求参数
 */
export function get(url: string, params?: any): Promise<AxiosResponse> | Promise<AxiosResponse<any>> {
    return new Promise((resolve, reject) => {
        server.get(url, {
            params: params
        }).then((res) => {
            resolve(res.data)
        }).catch((err) => {
            reject(err)
        })
    })
}


/**
 * 导出post请求方法
 * @url 请求地址
 * @params post请求参数
 */

export function post(url: string, params: any): Promise<AxiosResponse> | Promise<AxiosResponse<any>> {
    return new Promise((resolve, reject) => {
        server.post(url, qs.stringify(params)).then((res) => {
            resolve(res.data)
        }).catch((err) => {
            reject(err)
        })
    })
}

  1. 对后端接口进行集中管理(api.ts)
import  {get, post}  from "./https"

export const getHome = (params?: any) => get('/api/home', params)
export const postHome = (params: any) => post('/api/home', params)

  1. 在页面中调用api接口
// 引入
import { getHome } from "@/api/api.ts"

getHome({id: 1}).then((res :any) =>{
   console.log(res)
})

以上就是对axios的简单封装

posted @ 2020-12-06 10:12  boyyang  阅读(922)  评论(0编辑  收藏  举报
//黑猫咪:https://unpkg.com/live2d-widget-model-hijiki@1.0.5/assets/hijiki.model.json //白猫咪:https://unpkg.com/live2d-widget-model-tororo@1.0.5/assets/tororo.model.json //萌娘:https://unpkg.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json //狗狗:https://unpkg.com/live2d-widget-model-wanko@1.0.5/assets/wanko.model.json //萌妹1号:https://unpkg.com/live2d-widget-model-z16@1.0.5/assets/z16.model.json //萌妹2号:https://unpkg.com/live2d-widget-model-koharu@1.0.5/assets/koharu.model.json //萌妹3号:https://unpkg.com/live2d-widget-model-hibiki@1.0.5/assets/hibiki.model.json //妹子4号:https://unpkg.com/live2d-widget-model-izumi@1.0.5/assets/izumi.model.json //妹子5号:https://unpkg.com/live2d-widget-model-miku@1.0.5/assets/miku.model.json //6号:https://unpkg.com/live2d-widget-model-nico@1.0.5/assets/nico.model.json //7号:https://unpkg.com/live2d-widget-model-ni-j@1.0.5/assets/ni-j.model.json //8号:https://unpkg.com/live2d-widget-model-nipsilon@1.0.5/assets/nipsilon.model.json //9号:https://unpkg.com/live2d-widget-model-nito@1.0.5/assets/nito.model.json //10号:https://unpkg.com/live2d-widget-model-tsumiki@1.0.5/assets/tsumiki.model.json //11号:https://unpkg.com/live2d-widget-model-unitychan@1.0.5/assets/unitychan.model.json //帅哥1号:https://unpkg.com/live2d-widget-model-chitose@1.0.5/assets/chitose.model.json //帅哥2号:https://unpkg.com/live2d-widget-model-haruto@1.0.5/assets/haruto.model.json