鸿蒙开发中级1-axios的环境安装及网络请求用法
环境准备
终端进入项目目录,执行
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'}) 这里可以根据自身需要选择一种进行请求
本文是原创文章,完整转载请注明来自 MrXiao's Blog
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果