const http = {
     baseUrl:"本地或线上接口地址",
     request(config){
      config = beforeRequest(config)
      config.url = this.baseUrl+config.url
      return new Promise((resolve,reject)=>{
           uni.request(config).then(res=>{
                let [error,respon] = res
                const response = beforeRequest(respon)
                 resolve(response)
             }).catch(err=>{
                errorHand()
                reject(err)
             })

        })
},
  get(url,params,auth){
      //url:接口地址
      //params:查询参数
      //auth:请求是否需要携带token认证
      return this.reques({
          url:url,
          data:params,
          method:"GET",
          auth:auth
      })
  },
  delete(url,auth){
      return this.reques({
          url:url,
          method:"DELETE",
          auth:auth
      })
  },
  post(url,data,auth){
      //url:接口地址
      //data:请求参数
      //auth:请求是否需要携带token认证
      return this.reques({
          url:url,
          data:data,
          method:"POST",
          auth:auth
      })
  },
  put(url,data,auth){
      return this.reques({
          url:url,
          data:data,
          method:"PUT",
          auth:auth
      })
  }

}

 //请求拦截器
  const beforeRequest =(config)=>{
     return config
 },
 //响应拦截器
 const beforeRequest =(response)=>{
     return response
 },
 //异常处理器
 const errorHand = (err) =>{
 }

export default http

这个二次封装的基本内容,响应拦截器和请求拦截器中需要添加什么根据项目需求定

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐