在TypeScript中使用axios

331 阅读2分钟

为什么前端的项目要使用TypeScript, 我觉得因为JavaScript是弱类型,在编辑器中代码提示啊、类型错误无法识别,使用TypeScript,能在一定程度上减轻代码中的bug。 以下是我在使用TypeScript时候使用axios的一些使用记录。仅供参考。

第一步当然是安装axios

# yarn 或者 npm 都行
yarn add axios
npm install axios

第二步设置axios的声明文件

//声明响应体
// declare/req-res.d.ts
namespace ReqRes {
  /**
   * 定义接口返回的固定格式
   */
  export interface ResponseResult<T = any> {
    [propName: string]: T
  }
}
// 声明请求体
// declare/axios.d.ts

import {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosPromise
} from 'axios'
/// <reference path="./req-res.d.ts" />
/**
 * 自定义扩展axios模块
 */
declare module 'axios' {
  export interface AxiosInstance {
    request<T = any, R = ReqRes.ResponseResult<T>>(
      config: AxiosRequestConfig
    ): Promise<R>
    get<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      config?: AxiosRequestConfig
    ): Promise<R>
    delete<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      config?: AxiosRequestConfig
    ): Promise<R>
    head<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      config?: AxiosRequestConfig
    ): Promise<R>
    options<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      config?: AxiosRequestConfig
    ): Promise<R>
    post<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      data?: any,
      config?: AxiosRequestConfig
    ): Promise<R>
    put<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      data?: any,
      config?: AxiosRequestConfig
    ): Promise<R>
    patch<T = any, R = ReqRes.ResponseResult<T>>(
      url: string,
      data?: any,
      config?: AxiosRequestConfig
    ): Promise<R>
  }
}

第三步 封装统一请求文件

// utils/request.ts
import axios from 'axios'
import qs from 'qs'
import { VITE_API_URL } from '@/utils/config' //接口域名

//请求拦截
axios.interceptors.request.use(
  (config: any) => {
    return config
  },

  (err) => {
    return Promise.reject(err)
  }
)

//响应拦截
axios.interceptors.response.use(
  (response) => {
    const res = response.data
    return response
  },
  (err) => {
    return Promise.reject(err)
  }
)

export default {
  /**
   *
   * @param {string} url 接口地址 
   * @param {object} params 接口所需要携带的参数
   * @param {object} options axios 选项配置
   * @returns {promise}
   */
  get<T>(
    url: string,
    params: object = {},
    options?: object
  ) {
    if (JSON.stringify(params) !== '{}') {
      return axios.get<T>(
        `${VITE_API_URL}${url}?${qs.stringify(params)}`,
        {
          ...options
        }
      )
    } else {
      return axios.get<T>(`${VITE_API_URL}${url}`, {
        ...options
      })
    }
  },
  /**
   *
   * @param {string} url 接口地址 
   * @param {object} params 接口所需要携带的参数
   * @param {object} options axios 选项配置
   * @returns {promise}
   */
  post<T>(url: string, params = {}, options?: object) {
    return axios.post<T>(
      `${VITE_API_URL}${url}`,
      params,
      options
    )
  }
}


第四步 设置数据模型

// 1、定义公共的返回值
// model/base.ts
declare namespace ModelBase {
  //公共返回数据
  interface CommonResponse {
    code: string; //响应码,0:成功,否则异常
    msg: string; //响应信息
  }
}

// 2、
// model/login.ts
/// <reference path="./base.ts" />
declare namespace ModelLogin {
   //登录-请求
  interface LoginParams {
    captchaId: string; 
    codes: string;
    loginName: string; 
    passwd: string; 
  }
  //登录-响应
  interface LoginDataResponse {
    loginName: string; //登录账号
    token: string; //token
  }
  interface LoginResponse extends ModelBase.CommonResponse {
    data: LoginDataResponse;
  }
}

第五步 请求接口

//api/login.ts
import request from '@/utils/request'
///<reference path="../model/login.ts" />
/**
 * 登录
 * @param { ModelLogin.LoginParams } params
 * @returns { Promise }
 */
export async function userLogin(
  params: ModelLogin.LoginParams
) {
  return request.post<ModelLogin.LoginResponse>(
    '/login',
    params
  )
}

这时候只需要在页面中进行接口的请求,请求体和响应体也会有相应的提示(编辑器中)。