我有一个克隆的 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
})
)
}
我可以知道解决此错误的最佳方法。 希望对您有所帮助。谢谢
答案 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);
});