HarmonyOS 鸿蒙Next axios interceptors response如何使用ets实现

HarmonyOS 鸿蒙Next axios interceptors response如何使用ets实现 初次使用axios,目前也不清楚。它的error是什么类型。ts可以work,如何改造成ets

2 回复

/**

  • axios请求实例
  • 后续公共的数据缓存等在此配置 */ export const serviceAxios: axios.AxiosInstance = axios.default.create({ baseURL: BuildProfile.apihost, timeout: 10000, })

/**

  • 请求返回拦截器
  • 可以对公共异常的返回做拦截处理 */ serviceAxios.interceptors.response.use( (response: axios.AxiosResponse) => { // 打印返回日志 console.log(TAG, ===================== RESPONSE ==================== Status: ${response.status} Data: ${response.data}); return response }, (error: axios.AxiosError) => { if (error) { switch (error.message) { case AxiosError.ERR_NETWORK: case AxiosError.ERR_BAD_RESPONSE: case AxiosError.ERR_BAD_REQUEST: case AxiosError.ERR_NOT_SUPPORT: promptAction.showToast({ message: $r(‘app.string.request_error’) }); break case AxiosError.ERR_INVALID_URL: promptAction.showToast({ message: $r(‘app.string.url_invalide’) }); break case AxiosError.ERR_CANCELED: promptAction.showToast({ message: $r(‘app.string.request_cancel’) }); break case AxiosError.ECONNABORTED: case AxiosError.ETIMEDOUT: promptAction.showToast({ message: $r(‘app.string.request_abort’) }); break } } return Promise.reject(error) } )

error枚举

更多关于HarmonyOS 鸿蒙Next axios interceptors response如何使用ets实现的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙)系统中,使用ets(即eTS,Extended TypeScript)实现axios interceptors来拦截和处理响应,与在Web或Node.js环境中的实现方式有所不同,主要是因为鸿蒙系统有其特定的开发框架和API。

在ets环境中,若需实现类似axios interceptors的功能,通常你需要利用鸿蒙提供的网络请求API(如fetch)或者封装自己的网络请求库,并在请求或响应的处理过程中添加拦截逻辑。

由于ets是基于TypeScript的扩展,你可以利用Promise或async/await来处理异步请求,并在这些处理流程中添加你的拦截逻辑。例如,你可以创建一个自定义的网络请求函数,该函数在发送请求前和接收响应后执行特定的操作。

以下是一个简化的示例,展示了如何在ets中实现类似的拦截逻辑:

function customFetch(url: string, options?: RequestInit): Promise<Response> {
    // 发送请求前的拦截逻辑
    console.log('Sending request to:', url);

    return fetch(url, options).then(response => {
        // 接收响应后的拦截逻辑
        console.log('Received response:', response.status);
        return response;
    });
}

// 使用示例
customFetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

如果问题依旧没法解决请联系官网客服,官网地址是 https://www.itying.com/category-93-b0.html,

回到顶部