如何处理来自redux app的api调用中的> 400响应?

时间:2016-10-25 07:23:12

标签: reactjs redux fetch react-redux

目前我使用fetch在我的redux应用程序中进行api调用。

我尝试构建中间件api: -

export function api(endpoint,method,isAuth=false,body=null,multiPart=false,initToken=null)
{
  let promise = null
  let myHeaders = new Headers();
  if(!multiPart){
    myHeaders.append("Content-Type", "application/json");
  }


  if(isAuth){
    //if authorizations is needed adding header
      const accessToken = authentication.getAccessToken()
      myHeaders.append("Authorization",accessToken)
  }

  if(initToken){
    // in case of initToken adding to Authorization
    console.log("here"+initToken)
    myHeaders.append("Authorization",initToken)
  }

  let myInit = { method: method,headers: myHeaders};

  myInit['method'] = method
  myInit['headers'] = myHeaders

  if(body){
      myInit['body'] = body
  }


  let request = new Request(constants.BASE_URL+endpoint,myInit);
  promise = fetch(request)

  return promise
}

我在我的thunk中使用extraArguments

注入上述内容
export default function configureStore(initialState) {
  const store=createStore(
    rootReducer,
    initialState,
    compose(
      applyMiddleware(thunk.withExtraArgument(api),createLogger()),
      DevTools.instrument()
    ))
  return store
}

在我的行动中跟随api: -

export function fetchEmployeeInformation(){
  return (dispatch,getState,api) => {
        const endPoint = '//url'
        const  method = 'GET'
        const isAuth = true
        const promise = api(endPoint,method,isAuth)
        promise
        .then(response =>
          response.json().then(json => ({
            status:response.status ,
            json
          })
        ))
        .then(
          ({ status, json }) => {
            if( status >= 200 && status < 300) {
               //success
            }
            if (status >= 400 ) {
                //throw error
            }
          },
          err => {
            console.log("error"+err);
          }
        );
  }
}

所以我的问题是在angularjs中有任何类似$http的包,我可以在react-redux应用程序中使用它。我的意思是如果状态代码在200-299范围内,它应该使其成功或者抛出错误。

使用fetch我看到它并不关心代码,我必须专门检查代码范围是否高于&gt;然后抛出错误。

有没有更好的方法来解决这个问题?

2 个答案:

答案 0 :(得分:2)

图书馆axios与Angular $ http的流程类似,包括requestInterceptorresponseInterceptor。 阅读更多docs

答案 1 :(得分:1)

您还可以尝试frisbee,这是一个fetch API包装器。获得response对象后,您可以检查errok布尔属性。

异步示例:

const api = new Frisbee({
   baseURI: 'https://yourapiurl.com'
})
const rs = await api.get(`url`)
if (rs.ok) {
  console.log('success')
} else {
  console.log('failure', rs.err)
}

飞盘也可以与节点和React Native完美配合。