首页 > 其他分享 >Fetch封装

Fetch封装

时间:2023-03-09 20:36:01浏览次数:44  
标签:封装 url JSON Fetch json result error response

Fetch使用

Get=(url)=>{
    fetch(url)//默认是GET
        .then(response=>response.json())//把数据解析成json格式,然后取出
        .then(result=>{
            this.setState({
                result:JSON.stringify(result),//序列化:转换为一个 (字符串)JSON字符串
            });
        })
        .catch(error=>{
        this.setState({
            result:JSON.stringify(error),//把错误信息格式化为字符串
        });
    })
};

//模拟登陆Post
Post=(url,data)=>{
    fetch(url,{
        method:'POST',
        header:{
            'Accept':'application/json',//告诉服务器,我们能接受json格式的返回类型,
            'Content-Type':'application/json',//告诉服务器,我们提交的数据类型
        },
        body:JSON.stringify(data),//(把你想提交得数据序列化为json字符串类型,然后提交)body中的数据就是我们需要向服务器提交的数据,比如用户名,密码等
    })//返回 服务器处理的结果
        .then(response=>response.json())
        .then(result=>{
            this.setState({
                result:JSON.stringify(result),//序列化:转换为一个 (字符串)JSON字符串
            });
        })
        .catch(error=> {
            this.setState({
                result: JSON.stringify(error),//把错误信息格式化为字符串
            })
        })
};

HttpUtils页(封装的函数)

export default class HttpUtils{
static get=(url)=>{
    return new  Promise(((resolve, reject) => {//resolve 和 reject 函数被调用时,分别将promise的状态改为fulfilled(完成)或rejected(失败)
        fetch(url)//默认是GET
            .then(response=>response.json())//把数据解析成json格式,然后取出
            .then(result=>{
                   resolve(result);//表示完成
            })
            .catch(error=>{
                    reject(error);//表示失败
            })
        })
    )
};
static post=(url,data)=>{
    return new Promise(((resolve, reject) => {
        fetch(url,{
            method:'POST',
            header:{
                'Accept':'application/json',//告诉服务器,我们能接受json格式的返回类型,
                'Content-Type':'application/json',//告诉服务器,我们提交的数据类型
            },
            body:JSON.stringify(data),//(把你想提交得数据序列化为json字符串类型,然后提交)body中的数据就是我们需要向服务器提交的数据,比如用户名,密码等
        })//返回 服务器处理的结果
            .then(response=>response.json())
            .then(result=>{
                resolve(result);
            })
            .catch(error=> {
                reject(error);
            })
        })
    )
}
}//数据转换成字符串 JSON.stringify(params)      //将数据JSON化 JSON.parse(responseJSON)

重新调用

 Get=(url)=>{
    HttpUtils.get(url)//调用自定义组件方法,返回一个Promise
        .then(result=>{//then函数会返回一个新的promise
            this.setState({
                result:JSON.stringify(result),//序列化:转换为一个 (字符串)JSON字符串
            });
        })
        .catch(error=> {
            this.setState({
                result: JSON.stringify(error),//把错误信息格式化为字符串
            })
        })
};


Post=(url,data)=>{
    HttpUtils.post(url,data)
        .then(result=>{
            this.setState({
                result:JSON.stringify(result),//序列化:转换为一个 (字符串)JSON字符串
            });
        })
        .catch(error=> {
            this.setState({
                result: JSON.stringify(error),//把错误信息格式化为字符串
            })
        })
};

一、先看get全过程

  export async function get(url, props = null,timeout = 25000,showLoading = true) {
  const {isNetWorkConnected} = props
  if (!isNetWorkConnected) {
    messageModule.showMessage('网络连接不可用')
    return false
  }
  const token = await Storage.get('token', 'null')

  console.log('token == ',token)
  const fetchUrl = `${getAPPUrl()}${url}`
  if(showLoading){
    messageModule.showLoading('')
  }
  const fetchRequest = fetch(fetchUrl, {
    method: 'GET',
    headers: {
      'Authorization': token,
      'Content-Type': 'application/json',//告诉服务器,我们能接受json格式的返回类型,
      'Accept': 'application/json',//告诉服务器,我们提交的数据类型
    }
  })
  return new Promise((resolve) => {
    myFetch(fetchRequest,timeout)
      .then((response) => {
        mllog('getTimeOut response = ', response)
        if(showLoading){
          messageModule.hideHUD()
        }
        if (response.status === StatusCode.REFRESH_TOKEN_CODE) {// token过期,需要重新获取token
          getNewToken(response)
          return get(url, props,timeout)
        }
        return responseStatus(response, props)
      }).then(responseJson => {
      mllog('getTimeOut responseJson = ', responseJson)
      resolve(jsonStatus(responseJson))
    }).catch(error => {
      if(showLoading){
        messageModule.hideHUD()
      }
      messageModule.showMessage(`${error}`)
      mllog('getTimeOut fetch error = ', error)
      resolve(false)
    })
  })

}

 

  • 根据传递进来的属性判断网络是否连接
  • 2、获取存储的token
  • 3、fetchRequest设置请求url,method,请求头
  • 4、myFetch判断请求超时;token过期
  • 5、responseStatus(response, props)处理服务器返回的状态
  • 6、resolve(jsonStatus(responseJson))解析json状态
  • 7、返回失败resolve(false)

4、myFetch判断请求超时

Promse.race就是赛跑的意思,意思就是说,Promise.race([p1, p2, p3])里面哪个结果获得的快,就返回那个结果,不管结果本身是成功状态还是失败状态。

  const myFetch = (requestPromise, timeout) => (
    Promise.race([
      requestPromise,
      new Promise((resolve, reject) => {
        setTimeout(() => reject(new Error('网络不稳定')), timeout)
      })
    ])
  )

5、处理服务器返回的状态

  function responseStatus(response, props = null) {
    if (response.status === 401) { // token失效,跳转到登录界面
      if (props !== null) {
        messageModule.showMessage('账号异常,请重新登录')
        props.dispatch(createAction('app/clearLoginInfo')())//dva清楚登录信息
      }
      return false
    } else if (response.status !== 200) {// 网络请求异常
      messageModule.showMessage(`网络请求异常,请稍后重试${response.status}`)
      return false
    }
    return response.json() // 网络请求正常
  }

6、解析json状态

  function jsonStatus(json) {
    if (json.ret !== StatusCode.SUCCESS_CODE && json.ret !== '99999') {// 接口返回错误错误信息
      if (json.msg !== null && json.msg !== undefined) {
        messageModule.showMessage(json.msg)
      }
      return false
    }
    return json // 接口调用正常
  }

二、post

在fetchRequest里添加

  body: JSON.stringify(//把你想提交得数据序列化为json字符串类型,然后提交)body中的数据就是我们需要向服务器提交的数据,比如用户名,密码等
        params
      )

  

引用一

引用 二

  

  

 

 

标签:封装,url,JSON,Fetch,json,result,error,response
From: https://www.cnblogs.com/friend/p/17201286.html

相关文章