当前位置:   article > 正文

鸿蒙开发使用Axios_鸿蒙下载axios

鸿蒙下载axios

鸿蒙开发使用Axios

01.安装Axios

ohpm install @ohos/axios
  • 1

02.开启权限(module.json5)

"requestPermissions": [
    //开启网络权限
    {
        "name": "ohos.permission.INTERNET"
    },
  • 1
  • 2
  • 3
  • 4
  • 5

03.创建Axios实例

export const axiosInstance = axios.create({
  baseURL: BASE_URL, // 请求基地址
  timeout: 1000 * 20 // 请求超时时间
})
  • 1
  • 2
  • 3
  • 4

04.请求拦截器,响应拦截器

// 添加请求拦截器
axiosInstance.interceptors.request.use((config:InternalAxiosRequestConfig) => {
  // 对请求数据做点什么
  return config;
}, (error:AxiosError) => {
  // 对请求错误做些什么
  return Promise.reject(error);
});


// 添加响应拦截器
axiosInstance.interceptors.response.use((response:AxiosResponse)=> {
  // 对响应数据做点什么
  return response;
}, (error:AxiosError)=> {
  // 对响应错误做点什么
  return Promise.reject(error);
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

05.请求类型

用Axios的post的请求举个例子

interface user {
    firstName: string,
    lastName: string
}
//  第一个类型参数: 没啥用,会被第二个参数覆盖
//  第二个类型参数: 定义 后端返回数据  的类型 
//  第三个类型参数: 定义 post请求参数 的类型 
axiosInstance.post<string, AxiosResponse<string>, user>('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
})
    .then((response: AxiosResponse<string>) => {
    console.info(JSON.stringify(response));
})
    .catch((error) => {
    console.info(JSON.stringify(error));
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/878305
推荐阅读
相关标签
  

闽ICP备14008679号