1import { http } from "@kit.NetworkKit" 2 3/** 4 * 封装http请求 5 */ 6export function myRequest2(url: string, method: http.RequestMethod, requestData: string) { 7 // 创建http对象 8 const httpRequest = http.createHttp() 9 httpRequest.request(url, { 10 method: method, 11 header: { 12 // 前端传递数据格式 13 'Content-type': 'application/json' 14 }, 15 extraData: requestData, 16 connectTimeout: 6000, 17 readTimeout: 6000 18 }, 19 (error: Error, data: http.HttpResponse) => { 20 if (!error) { 21 console.log(JSON.stringify(data)) 22 } else { 23 console.log(`http error:${JSON.stringify(error)}`) 24 } 25 httpRequest.destroy() 26 }) 27}
1Button('发送请求').onClick((event:ClickEvent)=>{ 2 const url = 'http://www.yyxx.org/data.php?id=2' 3 myRequest2(url, http.RequestMethod.GET, '') 4})
1Button('发送请求').onClick(async (event: ClickEvent) => { 2 const url = '/data.php?id=2' 3 const res = await myRequest3(url, http.RequestMethod.GET, '') 4 console.log(res) 5})
Copyright ©2010-2022 比特日记 All Rights Reserved.
Powered By 可尔物语