http請求封裝
步驟
1、定義響應(yīng)數(shù)據(jù)格式
2、封裝數(shù)據(jù)請求
3、將各種請求進(jìn)行模塊劃分
4、請求示例
項(xiàng)目目錄
1、定義響應(yīng)數(shù)據(jù)格式
?export default class ?Response { ? ?/** ? ? * 響應(yīng)碼 ? ? */ ? ?code:number ? ?/** ? ? * 響應(yīng)消息 ? ? */ ? ?message:string ? ?/** ? ? * 響應(yīng)數(shù)據(jù) ? ? */ ? ?data:any ?}
2、封裝數(shù)據(jù)請求
提示:具體更詳細(xì)的配置請參考官網(wǎng)
?import http from '@ohos.net.http'; ?//導(dǎo)入預(yù)定好的數(shù)據(jù)響應(yīng)格式 ?import Response from '../utils/Response' ?? ?//導(dǎo)出去一個(gè)請求函數(shù),這樣開發(fā)者就可以像axios一樣的風(fēng)格請求數(shù)據(jù) ?export function request(url:string,method: http.RequestMethod,data?:any): Promise<Response> { ? ?//定義一個(gè)后臺請求的基地址 ? ?const BASE_URL = ?"http://localhost:9600" ? ?let httpRequest = http.createHttp(); ? ?let responseResult = httpRequest.request( BASE_URL+ url,{ ? ? ?method: method, ? ? ?// header: { ? ? ?// ? 'Content-Type': 'application/json' ? ? ?// }, ? ? ?//攜帶額外參數(shù) ? ? ?extraData: JSON.stringify(data), ? ? ?// 可選,指定返回?cái)?shù)據(jù)的類型 ? ? ?// expectDataType: http.HttpDataType.STRING, ? ? ?// 可選,默認(rèn)為true ? ? ?// usingCache: true, ? ? ?// 可選,默認(rèn)為1 ? ? ?// priority: 1, ? ? ?// 可選,默認(rèn)為60000ms ? ? ?// connectTimeout: 60000, ? ? ?// readTimeout: 60000, ? ? ?// 可選,協(xié)議類型默認(rèn)值由系統(tǒng)自動(dòng)指定 ? ? ?// usingProtocol: http.HttpProtocol.HTTP1_1, ? }); ?? ? ?let response = new Response(); ? ?// 處理數(shù)據(jù),并返回 ? ?return responseResult.then((value: http.HttpResponse) => { ? ? ?if (value.responseCode === 200) { ? ? ? ?// 獲取返回?cái)?shù)據(jù),將返回的json數(shù)據(jù)解析成事先預(yù)定好的響應(yīng)格式 ? ? ? ?// 這里建議和后端的保持一致 ? ? ? ?let res: Response = JSON.parse(`${value.result}`); ? ? ? ?response.data = res.data; ? ? ? ?response.code = res.code; ? ? ? ?response.message = res.message; ? ? } else { ? ? ? ?response.message = '請求錯(cuò)誤'; ? ? ? ?response.code = 400; ? ? } ? ? ?return response; ? }).catch(() => { ? ? ?response.message = '請求錯(cuò)誤'; ? ? ?response.code = 400; ? ? ?return response; ? }); ?}
3、將各種請求進(jìn)行模塊劃分
熟悉vue開發(fā)的同學(xué)都知道我們不同模塊的請求一般放在api目錄下進(jìn)行劃分
如下以請求用戶User模塊為示例文章來源:http://www.zghlxwxcb.cn/news/detail-763170.html
?import http from '@ohos.net.http'; ?//導(dǎo)入封裝好的請求 ?import { request } from '../utils/request' ?? ?/** ? * 根據(jù)用戶id請求用戶數(shù)據(jù) ? * @param userId ? * @returns ? */ ?export function getUserById(userId) { ? ?return request(`/user/get/${userId}`,http.RequestMethod.GET) ?} ?? ?/** ? * 請求用戶數(shù)據(jù) ? * @param userId ? * @returns ? */ ?export function getUser() { ? ?return request('/user/get',http.RequestMethod.GET) ?} ?? ?/** ? * 用戶數(shù)據(jù)保存 ? * @param userId ? * @returns ? */ ?export function save(data) { ? ?return request(`/user/save`,http.RequestMethod.POST,data) ?}
4、附上一個(gè)請求示例
這里提前一個(gè)用戶對象用于接收數(shù)據(jù)時(shí)使用文章來源地址http://www.zghlxwxcb.cn/news/detail-763170.html
?export default class User { ? ?username:string ? ?password:string ?}
?//導(dǎo)入api下的User模塊:請求方法 ?import {getUser,save,getUserById} from '../api/user' ?//導(dǎo)入定義好的用戶對象 ?import User from '../model/User' ?? ?@Entry ?@Component ?struct Index { ? ?@State user:User = { ? ? ?username: '', ? ? ?password: '' ? } ?? ? ? ?//組件展示前進(jìn)行數(shù)據(jù)的一個(gè)請求 ? ?aboutToAppear() { ? ? ?//根據(jù)用戶id進(jìn)行的一個(gè)請求 ? ? ?getUserById(1).then(res => { ? ? ? ?if(res.code === 200){ ? ? ? ? ?this.user = res.data ? ? ? } ? ? }) ? ? ?//不攜帶參數(shù)的一個(gè)請求 ? ? ?getUser().then(res => { ? ? ? ?if(res.code === 200){ ? ? ? ? ?this.user = res.data ? ? ? } ? ? }) ? } ?? ? ?build() { ? ? ?Row() { ? ? ? ?Column() { ? ? ? ? ?Text(this.user.username) ? ? ? ? ? .fontSize(30) ? ? ? ? ? .fontWeight(FontWeight.Bold) ? ? ? ? ?Text(this.user.password) ? ? ? ? ? .fontSize(30) ? ? ? ? ? .fontWeight(FontWeight.Bold) ?? ? ? ? ? ?Divider() ? ? ? ? ?TextInput().margin({ top: 20 }) ? ? ? ? ? .onChange((value: string) => { ? ? ? ? ? ? ?this.user.username = value ? ? ? ? ? }) ? ? ? ? ?TextInput().type(InputType.Password).margin({ top: 20 }) ? ? ? ? ? .onChange((value: string) => { ? ? ? ? ? ? ?this.user.password = value ? ? ? ? ? }) ? ? ? ? ?Button('登錄').width(150).margin({ top: 20 }) ? ? ? ? ? .onClick(()=> { ? ? ? ? ? ? ?console.log("發(fā)送成功") ? ? ? ? ? ? ?//保存用戶數(shù)據(jù)的一個(gè)請求 ? ? ? ? ? ? ?save(this.user) ? ? ? ? ? }) ? ? ? } ? ? ? .width('100%') ? ? ? .height('100%') ? ? ? .padding({top: 50}) ? ? } ? ? .height('100%') ? ? .width('100%') ? ? .alignItems(VerticalAlign.Top) ? } ?}
到了這里,關(guān)于鴻蒙 HarmonyOS4.0 Http數(shù)據(jù)請求封裝詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!