import { InternalAxiosRequestConfig, AxiosResponse, AxiosError } from "@ohos/axios" import promptAction from '@ohos.promptAction' // 是否在控制台打印某项log const pConfig = false const pHeaders = false const pUrl = true const pParams = true const pBody = true const pResponse = true const pData = true const pError = true // @CustomDialog // struct CustomDialogExample { // controller: CustomDialogController // build() { // Column() { // Text('我是内容') // .fontSize(20) // .margin({ top: 10, bottom: 10 }) // } // } // } const printRequest = (config: InternalAxiosRequestConfig) => { if (pConfig) { console.debug("printRequest config", JSON.stringify(config)) } if (pHeaders) { console.debug("printRequest headers", JSON.stringify(config.headers)) } if (pUrl) { console.debug("printRequest url", `Method:${config.method} ${config.baseURL}${config.url}`) } if (pBody) { console.debug("printRequest 请求参数data", JSON.stringify(config.data)) } if (pParams) { console.debug("printRequest 请求参数params", JSON.stringify(config.params)) } } const printResponse = (response: AxiosResponse) => { if (pResponse) { console.debug('printResponse response: ', JSON.stringify(response)) } if (pData) { console.debug("printResponse data", JSON.stringify(response.data)) } } const printError = (error: AxiosError) => { if (pError) { console.debug("printError error", error.message) } promptAction.showToast({ message: error.message ?? "请求出错", duration: 1500, bottom: 100 }) } // 处理返回数据 const handleRes = (response: AxiosResponse): [boolean, string] => { let isSuccess = true let msg = "" if (response.status === 200) { //判断返回状态是否为200 if (String(response.data?.code) === "200") { //判断数据的code是否为200,有可能是500的服务器错误 isSuccess = true msg = `请求数据成功` } else { isSuccess = false // msg = `${response.data?.code}: ${response.data?.msg ?? "服务器错误"}` msg = `${response.data?.msg ?? "服务器错误"}` } } else { isSuccess = false msg = `状态码非200 status: ${response.status}}` } if (!isSuccess) { promptAction.showToast({ message: msg, duration: 2000, bottom: 100 }) // const dialogController: CustomDialogController = new CustomDialogController({ // builder: CustomDialogExample({}), // }) // dialogController.open() } return [isSuccess, msg] } export { printRequest, printResponse, printError, handleRes }