环境准备

终端进入项目目录,执行

ohpm install @ohos/axios  

核心方法

requestHttp(method: http.RequestMethod, url: string, param?: object): Promise<object> {
  return new Promise((resolve, reject) => {
    if (url.length <= 0) {
      debugLog('url错误,请检查')
      reject('url错误,请检查')
    }
    url = Debug_BaseUrl + url;
    axios.post(url, param
    )
      .then((obj: AxiosResponse) => {
        debugLog(json.stringify(obj.data))
        const objDic = obj.data as object
        if (objDic['code'] == 200) { // 请求成功
          debugLog(objDic['message'])
          AlertDialog.show({ message: objDic['message'] })
          resolve(objDic['data'])
        } else if (objDic['code'] == 500) { // 请求失败
          debugLog(objDic['message']['error_msg'])
          AlertDialog.show({ message: objDic['message']['error_msg'] })
          resolve(objDic['data'])
        }
      })
      .catch((error: AxiosError) => {
        debugLog(error)
        reject(error)
      })
  })

GET请求

axios({
  url: yourUrl,
  method: 'get',
  param: Object({'key': 'value'})
})
  .then((obj: AxiosResponse) => {
    debugLog(json.stringify(obj.data))
  })
  .catch((error: AxiosError) => {
    debugLog(error)
  })

POST请求

这里一点需要注意的是data包含的方法 需要用Object()包装一下 否则 数据无法传递给后端

axios({
  url: yourUrl,
  method: 'post',
  data: Object({'key': 'value'})
})
  .then((obj: AxiosResponse) => {
    debugLog(json.stringify(obj.data))
  })
  .catch((error: AxiosError) => {
    debugLog(error)
  })

axios是支持两种方式进行请求是的

一种是axios.get 或者axios.post 另外一种是axiox({method: 'post'}) 这里可以根据自身需要选择一种进行请求