在开发中我们很多地方都会用到网络请求,为了开发方便,我们可以对网络请求进行封装,下面是根据我最近练习的项目封装的一个网络请求,可以根据你的需求进行修改

//导入模块
import {http} from "@kit.NetworkKit"

//封装http请求
class myHttp{

  //设置一个变量,当你创建实例时传入你项目的baseURL
  private baseURL:string=""
  constructor(baseURL:string) {
    this.baseURL=baseURL
  }  
  
  //一些请求头常量,根据要求修改
  private AppId:string="你项目一些识别应用的ID"
  private AppKey:string="根据需求传入"
  private mastKey:string="根据需求传入"
  
  // get请求方法(url必传,传进来自动与baseurl拼接,其他可选,当你需要传后面可选的时候前面的可选要传空)
  get(url:string, params?:string, masterKey?:string, token?:string,){
    const httpRequest=http.createHttp();  //构建一个http请求实例
    console.log(url,params,masterKey,token) //可以查看你传入的东西符不符合预期
    return httpRequest.request(this.baseURL+url,{    //发起http请求,返回promise
      method:http.RequestMethod.GET,  //请求方式
      extraData:params?JSON.parse(params):null,  //参数
      header:{   //请求头
        'X-LC-Id': this.AppId,  
        'X-LC-Key':masterKey?masterKey+",master":this.AppKey, 
        'Content-Type': 'application/json',
        "X-LC-Session":token?token:null,
      }
    })
  }

  //post请求方法
  post(url:string,params?:string,masterKey?:string,token?:string){
    const httpRequest=http.createHttp();
    console.log(url,params,masterKey,token)
    return httpRequest.request(this.baseURL+url,{  //和你传入的url做拼接
      method:http.RequestMethod.POST,
      extraData:params?JSON.parse(params):null,
      header:{
        'X-LC-Id': this.AppId,
        'X-LC-Key': masterKey?masterKey+",master":this.AppKey,
        'Content-Type': 'application/json',
        "X-LC-Session":token?token:null
      }
    })
  }

  //put请求方法
  put(url:string,sessionToken?:string,params?:string){
    const httpRequest=http.createHttp();
    return httpRequest.request(this.baseURL+url,{
      method:http.RequestMethod.PUT,
      extraData:JSON.parse(params),
      header:{
        'X-LC-Id': this.AppId,
        'X-LC-Key': this.AppKey,
        'Content-Type': 'application/json',
        "X-LC-Session":sessionToken?sessionToken:null
      }
    })
  }

  //delete请求
  delete(url:string,params?:string,masterKey?:string){
    console.log(url,params,masterKey)
    const httpRequest=http.createHttp();
    return httpRequest.request(this.baseURL+url,{
      method:http.RequestMethod.DELETE,
      extraData:params?JSON.parse(params):null,
      header:{
        'X-LC-Id':this.AppId,
        'X-LC-Key': masterKey?masterKey+",master":this.AppKey,
      }
  })
}

}
export default myHttp; //对外开放


//在页面需要用到请求时。举例:
Request=new myHttp("baseURL")
发送请求时(比如get请求)
this.Request.get("url",params).then(()=>{处理逻辑,比如处理后端数据})


这样封装的好处,当你用到不同服务器请求时,只需要修改baseURL即可,传入对应的url和实际开发需要的参数或者header。

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐