axios官方中文文檔:http://www.axios-js.com/
案例代碼:https://gitee.com/flymini/web-codes01/tree/master/axios_/learn-axios01
****
axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。axios 的使用非常簡單,按照官方文檔使用即可。下面提供封裝 axios 的一個案例,步驟如下:
<br/>
**1. 封裝`src/http/request.ts`**
```ts
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"
/**
* 定義返回值類型
*/
export interface Result<T = any> {
code: number
msg: string
data: T
}
class request {
//axios實例
private instance: AxiosInstance
//構造函數里面初始化
constructor(config: AxiosRequestConfig) {
this.instance = axios.create(config)
//定義攔截器
this.interceptors()
}
//攔截器
private interceptors() {
//axios發送請求之前的處理
this.instance.interceptors.request.use((config: AxiosRequestConfig) => {
//在請求頭部攜帶token
config.headers = {
token: 'token20221010'
}
return config
}, (error: any) => {
console.error(error)
return error
})
//請求返回之后的處理
this.instance.interceptors.response.use((res: AxiosResponse) => {
//獲取返回之后的數據
console.log(res.data)
return res.data
}, (error) => {
console.error(error)
return Promise.reject(error)
})
}
service<T>(config: AxiosRequestConfig): Promise<T> {
return new Promise((resolve, reject) => {
this.instance
.request<any, T>(config)
.then((res) => {
resolve(res)
})
.catch((error) => {
reject(error)
return error
})
})
}
//get請求
get<T = Result>(config: AxiosRequestConfig): Promise<T> {
return this.service<T>({ ...config, method: 'GET' })
}
//post請求
post<T = Result>(config: AxiosRequestConfig): Promise<T> {
return this.service<T>({ ...config, method: 'POST' })
}
//delete請求
delete<T = Result>(config: AxiosRequestConfig): Promise<T> {
return this.service<T>({ ...config, method: 'DELETE' })
}
//put請求
put<T = Result>(config: AxiosRequestConfig): Promise<T> {
return this.service<T>({ ...config, method: 'PUT' })
}
}
export default request
```
**2. 封裝`src/http/index.ts`**
```ts
import request from "./request"
const http = new request({
baseURL: 'http://127.0.0.1:5173',
})
export default http
```
**3. 調用方法發起請求**
```ts
import http from './http/index'
http
.post({ url: '/src/assets/student.json' })
.then((res: any) => {
console.log(res)
})
.catch((error: any) => {
console.log(error)
})
```
- nodejs
- 同時安裝多個node版本
- Vue3
- 創建Vue3項目
- 使用 vue-cli 創建
- 使用 vite 創建
- 常用的Composition API
- setup
- ref
- reactive
- 響應數據原理
- setup細節
- reactive與ref細節
- 計算屬性與監視
- 生命周期函數
- toRefs
- 其它的Composition API
- shallowReactive與shallowRef
- readonly與shallowReadonly
- toRaw與markRaw
- toRef
- customRef
- provide與inject
- 響應式數據的判斷
- 組件
- Fragment片斷
- Teleport瞬移
- Suspense
- ES6
- Promise對象
- Promise作用
- 狀態與過程
- 基本使用
- 常用API
- async與await
- Axios