一、先看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)
    })
  })
}
- 1、根据传递进来的属性判断网络是否连接
- 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
      )










网友评论