【HarmonyOS】鸿蒙开发之HTTP网络请求——第5章

HTTP网络请求封装

network/request.ets

bash 复制代码
import { configInterface } from './type'
import http from '@ohos.net.http'
import { getToken } from '../utils/storage'

//网络请求封装
export const request = (config:configInterface)=>{
  let httpRequest:http.HttpRequest = http.createHttp()
  let method:http.RequestMethod = config.method.toLowerCase()=='get'?http.RequestMethod.GET:http.RequestMethod.POST
  let header = {}
  let Token = getToken()
  if(config.headers){
    header={
      ...config.headers,
      'X-CSRF-TOKEN': `VueCms_xg ${Token}`,
      'Authorization': `Bearer vuecms.cn`,
    }
  }else if(!config.headers){
    config.headers={
      "Content-Type": "application/json"
    }
  }
  console.log('http://localhost:3000' + config.url,"32333333333");
  let response = httpRequest.request(
    // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
    // config.url,
    "http://localhost:3000"+config.url,
    {
      method, // 可选,默认为http.RequestMethod.GET
      // 开发者根据自身业务需要添加header字段
      header,
      extraData:{...config.data},
      expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
    });
  return response.then((res:any)=>{
    let resultData:any = {}
    // 取消订阅HTTP响应头事件
    httpRequest.off('headersReceive');
    // 当该请求使用完毕时,调用destroy方法主动销毁
    httpRequest.destroy();

    let result:any = JSON.parse(res.result);
    console.log(result.code);
    if (result.code === 403) {
      console.log("登录状态已过期,您可以继续留在该页面,或者重新登录");
      // model.handleMsgBox('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
      //   confirmButtonText: '重新登录',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   userStore.LogOut().then(() => {
      //     location.href = "/login";
      //   })
      // })
    }
    resultData = {
      code:result.code,
      data:result.data,
      message:result.message,
    }
    return Promise.resolve(resultData)
  }).catch(err=>{
    console.log(JSON.stringify(err),"errrrrr111rrr");
    // 取消订阅HTTP响应头事件
    httpRequest.off('headersReceive');
    // 当该请求使用完毕时,调用destroy方法主动销毁。
    httpRequest.destroy();
    return new Promise((resolve,reject)=>{
      let res = {
        code:err.code,
        data:"",
        message:err.message,
      }
      reject(res)
    })
  })
}

network/type/index.ts 网络请求文件的typescript文件

bash 复制代码
export type methodsData = "post" | "get"
interface downloadParamsInterface{
  url: string
  params?: any
  filename: string
  isPost?: boolean
}
export interface configInterface{
  url: string
  data?: any
  method?: methodsData
  headers?: any
  downloadData?:downloadParamsInterface
}
export interface responseInterface {
  data:any
  message:string
  code:Number
}

实战项目使用

登录页的网络请求文件

ets/network/login/index.ts

登录页使用

ets/pages/login/index.ets

注意:

  1. 浏览器暂不支持网络请求,只能在模拟器或真机进行
  2. 请求需要申请ohos.permission.INTERNET 权限
  3. 网络请求限定并发个数为100,超过这一限制的后续请求会失败。
  4. 默认支持https ,如果要支持http,需要在module.json5 里添加network 标签

✨ 踩坑不易,还希望各位大佬支持一下 \textcolor{gray}{踩坑不易,还希望各位大佬支持一下} 踩坑不易,还希望各位大佬支持一下

📃 个人主页: \textcolor{green}{个人主页:} 个人主页: 沉默小管

📃 个人网站: \textcolor{green}{个人网站:} 个人网站: 沉默小管

📃 个人导航网站: \textcolor{green}{个人导航网站:} 个人导航网站: 沉默小管导航网

📃 我的开源项目: \textcolor{green}{我的开源项目:} 我的开源项目: vueCms.cn

🔥 技术交流 Q Q 群: 837051545 \textcolor{green}{技术交流QQ群:837051545} 技术交流QQ群:837051545

👍 点赞,你的认可是我创作的动力! \textcolor{green}{点赞,你的认可是我创作的动力!} 点赞,你的认可是我创作的动力!

⭐️ 收藏,你的青睐是我努力的方向! \textcolor{green}{收藏,你的青睐是我努力的方向!} 收藏,你的青睐是我努力的方向!

✏️ 评论,你的意见是我进步的财富! \textcolor{green}{评论,你的意见是我进步的财富!} 评论,你的意见是我进步的财富!

如果有不懂可以留言,我看到了应该会回复

如有错误,请多多指教

相关推荐
长按助力退休3 小时前
HTTP缓存从强缓存到协商缓存,前端性能优化第一步
http
物联网软硬件开发-轨物科技4 小时前
【轨物洞见】什么是产品碳足迹(PCF)?ISO 14067 计算方法与应用场景深度解读
大数据·网络·人工智能
姜鱼问生7 小时前
docker exec 排查容器问题:从日志到进程
运维·网络·数据库·docker·容器
qq_543447827 小时前
DNS解析怎么排查?故障处理与运维实用手册
运维·服务器·网络·php
刘马想放假8 小时前
网络链路备份与高可用技术详解:从 Dual-WAN、LACP 到 SD-WAN 与 MPTCP
网络协议
Zelman8 小时前
第07章-数据中心网络
后端·网络协议
OH_TPC9 小时前
【鸿蒙优选三方库】@ohos/aki:一行代码让 ArkTS 调 C++
harmonyos
wenyiyiyiyiyi9 小时前
我用鸿蒙 ArkTS 写了个自己天天用的备忘录:待办、课表和长期目标,全塞进一块桌面卡片
harmonyos
威胁猎人9 小时前
网络水军产业风险研究报告
网络
独钓寒江雨9 小时前
路由器单MAC多IP支持功能未开启致业务异常
网络·数通·故障·中兴·m6000·单mac多ip