ant design pro 修改request请求方法,修改为符合实际业务接口请求的数据处理方式

ant design pro 修改request请求方法,修改为符合实际业务接口请求的数据处理方式

ant design pro中对fetch进行了封装处理,写在utils/request.js,但是与我们通常的接口格式的处理并不适配,我们业务出现的错误代码并不会直接放在网络层,而是放在json中,所以需要做一些修改

原本写法

在ant design pro的项目中,原本的请求处理中可以看出,项目里把所有错误的情况都放在了网络请求错误码中,各种错误状态都在响应头status code中展现,所以原本的utils/request.js中的方法封装是这么写的

//这里的写的是响应头的status code如果不是200-300之间,直接抛出错误
const checkStatus = response => {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const errortext = codeMessage[response.status] || response.statusText;
  notification.error({
    message: `请求错误 ${response.status}: ${response.url}`,
    description: errortext,
  });
  const error = new Error(errortext);
  error.name = response.status;
  error.response = response;
  throw error;
};

... //中间省略不解释

//fetch封装
 return fetch(url, newOptions)
    .then(checkStatus)
    .then(response => cachedSave(response, hashcode))
    .then(response => {
    //进入then中时除了方法为DELETE或者204输出字符串,其他结果都是直接输出json字符串
      // DELETE and 204 do not return data by default
      // using .json will report an error.
      if (newOptions.method === 'DELETE' || response.status === 204) {
        return response.text();
      }
      return response.json();
    })
    .catch(e => {
     //这里捕获的是网络层的错误代码,对不同状态进行处理
      const status = e.name;
      if (status === 401) {
        // @HACK
        /* eslint-disable no-underscore-dangle */
        window.g_app._store.dispatch({
          type: 'login/logout',
        });
        return;
      }
      // environment should not be used
      if (status === 403) {
        router.push('/exception/403');
        return;
      }
      if (status <= 504 && status >= 500) {
        router.push('/exception/500');
        return;
      }
      if (status >= 404 && status < 422) {
        router.push('/exception/404');
      }
    });
}

在这种写法下,我们通常还需要在外面判断json内的状态码是否是200 ,来判断是否进行接下来的操作,这样写起来很麻烦,属于重复操作,所以需要对其进行修改


修改后

我们的项目中的返回格式通常是这样的

//错误状态格式
{
    code: 500
    data: null
    message: "系统异常,请稍后重试"
}

// 请求成功的代码
code: 200
data: {...}
message: "success"

所以我做了以下修改

//在这里对网络层的错误进行处理,200-400直接返回结果,网络层的错误情况统一处理
const checkStatus = response => {
  if (response.status >= 200  && response.status < 400) {
    return response;
  }
  const errortext = codeMessage[response.status] || response.statusText;
  notification.error({
    message: `请求错误 ${response.status}: ${response.url}`,
    description: errortext,
  });
  if (status === 401) {
    // @HACK
    /* eslint-disable no-underscore-dangle */
    window.g_app._store.dispatch({
      type: 'login/logout',
    });
  }
  // environment should not be used
  if (status === 403) {
    router.push('/exception/403');
  }
  if (status <= 504 && status >= 500) {
    router.push('/exception/500');
  }
  if (status >= 404 && status < 422) {
    router.push('/exception/404');
  }
  const error = new Error(errortext);
  error.name = response.status;
  error.response = response;
};

... //省略中间部分

 return fetch(url, newOptions)
    .then(checkStatus)
    .then(response => cachedSave(response, hashcode))
    .then(response => {
    //先将json返回,由下面的then接收
      // DELETE and 204 do not return data by default
      // using .json will report an error.
      if (newOptions.method === 'DELETE' || response.status === 204) {
        return response.text();
      }
      return response.json();
    })
    .then(response => {
    //对返回数据里面的状态码进行处理,200返回response内的data数据,其他状态部分统一处理,并抛出错误
      if(!response.code) { //这是针对之前的mock接口做的适应
        return  response
      }
      if(response.code == 200) {
        return  response.data
      }else {
        const status = response.code;
        if (status === 401) {
          // @HACK
          /* eslint-disable no-underscore-dangle */
          window.g_app._store.dispatch({
            type: 'login/logout',
          });
          return;
        }
        message.error(response.message);
        throw response
      }
    })

可以看到我上面并没有捕获错误,也就是没有写catch,这样就是为了在外部可以通过try..catch...来判断json内的code是否是200 从而做不同的处理,省去了if判断。下面是effect中的使用

try {
   yield call(updateUser, payload); 
   message.success('修改成功'); //上面的异步请求成功了,才会执行下面的代码
}catch(e) {
	...//自己的错误处理,也可以什么都处理
}

上面就是我的处理方式,但是肯定还有不同的处理方式,如果有更好的处理方式可以和我说下,当然返回数据也有不一样,可以根据自己的需求进行修改。

你可能感兴趣的:(前端笔记,解决问题,react,ant-design,ant,design,pro)