💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
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) }) ```