Blog
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)

HiuZing

🍑
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)
  • 前端面试题

  • JavaScript

  • Vue2

  • port

  • CSS

  • Node.js

  • JavaScript优化

  • uniapp

  • Mini Program

  • TypeScript

    • 基础

    • 实例

      • 登录表单
      • axios
        • Axios几个常用类型
          • AxiosRequestConfig
          • AxiosInstance
          • AxiosResponse
          • AxiosError
          • CreateAxiosDefaults
  • JavaScript 面向对象

  • UI组件

  • Plugin

  • Vue3

  • 性能优化

  • Axios

  • 状态管理

  • React

  • Mock

  • Icon

  • Template

  • 构建工具

  • 项目规范配置

  • Taro

  • SVG

  • React Native

  • Three.js

  • 前端
  • TypeScript
  • 实例
HiuZing
2023-04-12
目录

axios

# Axios几个常用类型

# AxiosRequestConfig

使用axios发送请求传递参数的类型,也是我们请求拦截器里面的参数类型

import axios, { AxiosRequestConfig } from 'axios'

const config: AxiosRequestConfig = {
  url:"/api/list",
  method:"GET",
  params:{ page:1 }
}
axios(config)


// interceptors.request.use 第一个参数类型就是 AxiosRequestConfig
axios.interceptors.request.use((config:AxiosRequestConfig)=>{
  config.headers.Authorization = "tokenxxx"
  return config
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# AxiosInstance

使用axios实例对象类型

import axios, { AxiosInstance } from "axios"

const service: AxiosInstance = axios.create({
  baseURL:"/api",
  timeout:10000
})
// service.get / service.post,给这个实例注册拦截器
service.interceptors.request.use(...)
1
2
3
4
5
6
7
8

# AxiosResponse

请求返回值类型都是AxiosResponse类型,并且我们可以发现AxiosResponse是一个接口泛型,这个泛型会应用到后端返回的data上

{
  data: T,    // ✔后端真实返回业务数据(泛型T)
  status: number, // http状态码 200
  statusText: string,
  headers: object,
  config: AxiosRequestConfig
}

interface UserItem {
  id:number
  name:string
}

// AxiosResponse<UserItem>,此时 res.data 类型就是 UserItem
async function getUser(){
  const res = await service.get<AxiosResponse<UserItem>>("/user")
  // 简化写法,get的泛型直接写业务类型
  // const res = await service.get<UserItem>("/user")
  console.log(res.data.id)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# AxiosError

响应拦截器里面的错误

import { AxiosError } from "axios"

// 响应拦截器错误捕获
service.interceptors.response.use(
  res=>res,
  (err:AxiosError)=>{
    if(err.response?.status === 401){
      // token过期
    }
    return Promise.reject(err)
  }
)
1
2
3
4
5
6
7
8
9
10
11
12

# CreateAxiosDefaults

传给axios.create()的配置类型,和 AxiosRequestConfig 很像,用于创建实例时候的默认全局配置。

import { CreateAxiosDefaults } from 'axios'
const opts:CreateAxiosDefaults = { baseURL:"" }
axios.create(opts)
1
2
3
上次更新: 2026/08/19, 01:24:11
登录表单
简介

← 登录表单 简介→

最近更新
01
React性能优化
08-18
02
记录一些描述
08-18
03
Swift入门
08-17
更多文章>
Theme by Vdoing | Copyright © 2021-2026 WeiXiaojing | 友情链接
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式