实战04-http请求
http.ts
import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios';
const request = axios.create({
baseURL: 'http://192.168.1.7:8001/demo/lx', // 通过 ipconfig 查询当前电脑的 ip,使用自己电脑的 ip 地址
timeout: 20000,
})
request.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
// 未来需要添加 token
// config.headers.token = token;
return config;
}
)
request.interceptors.response.use(
(response: AxiosResponse) => {
if (response.data.code === 200) {
return response.data.data;
} else {
return Promise.reject(response.data.message);
}
},
(error: AxiosError) => {
return Promise.reject(error.message);
}
)
export default class Http {
get<T>(url: string, params?: Object) {
return request.get<null, T>(url, {
params
})
}
post<T>(url: string, data?: Object) {
return request.post<null, T>(url, data)
}
put<T>(url: string, data?: Object) {
return request.put<null, T>(url, data)
}
delete<T>(url: string, params?: Object) {
return request.delete<null, T>(url, {
params
})
}
};
home.ts import Http from '../utils/http'; import { HomeData } from './models/HomeData'; const http = new Http(); //获取首页数据 export const getHomeDataApi = () => { return http.get<HomeData>('home/info') }
HomeDate.ts export interface HomeData { "bannerList": IBannerList "navList": INavList "titleList": ITitleList "planList": IPlanList "adPicTure": string } export interface IBannerItem { "id": number, "name": string, "imageURL": string } export type IBannerList = IBannerItem[] export interface INavItem { "id": number, "title": string, "imageURL": string } export type INavList = INavItem[] export interface ITitleItem { "id": number "imageURL": string "title": string "sub_title": string } export type ITitleList = ITitleItem[] export interface IPlanItem { "id": number "imageURL": string } export type IPlanList = IPlanItem[]
根据自己的情况去改动改动。。我是写的也不规范。我也是个新手