赞
踩
request.ts:
// 参考:https://www.jb51.net/article/282238.htm import axios from 'axios' const instance = axios.create({ baseURL: 'https://api.apiopen.top/api' }) // 添加请求拦截器 instance.interceptors.request.use(function (config) { // 在发送请求之前做些什么 return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); }); // 添加响应拦截器 instance.interceptors.response.use(function (response) { // 对响应数据做点什么 console.log('response', response) return response; }, function (error) { // 服务器状态码不是200的情况 // 对响应错误做点什么 return Promise.reject(error); }); export default instance
http.ts
import {AxiosResponse} from 'axios' import instance from './request' import QS from 'qs' // 后端传来的数据格式 type Data<T> = { code: number, message: string, result: T } export function get<T>(url: string, params: object) { return instance.get<Data<T>, AxiosResponse<Data<T>>>(url, { params }) } export function post<T>(url: string, data: object) { return instance.post<Data<T>, AxiosResponse<Data<T>>>(url, QS.stringify(data)) }