Axios-返回响应和错误响应

时间:2020-10-21 15:29:58

标签: reactjs axios

我一直在使用axios来处理服务-我现在处于集成阶段,需要返回服务器端错误。但是-我的动作函数需要返回响应-我尝试将axios部分包装在异步函数中,但是没有用。 https://github.com/axios/axios ^在这里遵循指南

我的actions.js中的当前代码块因此不得不注释掉-“ return serverResponse;”

export function activateUser(data) {

  let url = CONFIG.ACTIVATE_API;
  return function (dispatch) {
    //let serverResponse = "";
    axios.post(url, data)
    .then(function (response) {
      if(response.data.status === "success"){
        dispatch(regActivateSuccess(response));
      }
      else{
        dispatch(regActivateFail(response));//fail - user already in the system for example
      }
      return response;
    })
    .catch(function (error) {
      dispatch(regActivateFail(error.response));
    });

    //return serverResponse;
  }
}

在页面本身中-我试图在其中调用该服务-然后评估其是否有错误-

我的componentDidMount

//needs activation token?
let token = this.props.match.params.token;
let data7 = {"activation_token": token}

let awaiting = this.activateTheUser(data7);

let that = this;    
awaiting.then(function(result) {
  console.log("result", result);

   if(result === undefined){
     that.setState({
        errorMsg: "An error occured - user activation could not happen"
     });      
   }
})
.catch(function(error){
  that.setState({
    errorMsg: "An error occured - could not authenticate"
  });  
});

---这是异步的将其作为诺言

  async activateTheUser(data){
    return this.props.activateUser(data)  //so this is what is calling the function in the actions --
  }

0 个答案:

没有答案