可能的未处理的承诺拒绝(Id:0):TypeError:undefined不是对象(评估'err.response.data')

时间:2019-05-20 03:40:55

标签: javascript node.js mongodb react-native expo

我有一个克隆的 React Native 应用程序。它使用 Node.js API MongoDB 连接。但是,在注册到应用程序后,它无法从 MongoDB 插入或获取数据。另外,在我的模拟器上,屏幕底部出现黄色错误,提示:

  

可能的未处理的承诺拒绝(id:0):TypeError:未定义不是对象(正在评估“ err.response.data”)

这是我的代码:

export const loginuser = userData => dispatch => {
    axios.post("http://localhost:4000/api/users/login", userData)
      .then(res => {

        // save user token to local storage 
        const { token } = res.data;

        AsyncStorage.setItem("jwtToken", token);
        console.log(AsyncStorage.setItem())

        // set token to auth header i.e authorization 
        setAuthToken(token);

        // decode the token and saveuser to deoded

        const decoded = jwt_decode(token);
        console.log(token)
        //set current user 

        console.log(decoded)
        dispatch(setCurrentUser(decoded));

        Actions.main()
      })
      .catch(err => dispatch({
        type:GET_ERRORS,
        payload: err.response.data
      })
      )
  }

我可以知道解决此错误的最佳方法。 希望对您有所帮助。谢谢

1 个答案:

答案 0 :(得分:0)

请与Axios文档核对如何处理错误: https://github.com/axios/axios#handling-errors

err.response可能为空:

axios.post("http://localhost:4000/api/users/login", userData)
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });