我正在使用带有node.js后端的react-redux开发一个Web应用程序。我正在添加页面以将游戏添加到个人资料。运行此代码时出现错误。
这是我收到错误时正在使用的操作
export const addGames = (gameData, history) => dispatch => {
axios
.post("/api/profile/games", gameData)
.then(res => history.push("/dashboard"))
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
页面本身加载正常。只有在调用该操作时,它才会出错。错误时指向catch语句。
通过邮递员进行API调用会按预期返回,并且不会出错。
我得到的错误是
×
Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
eval
C:\dev\SocialNetworkTutorial\devConnector\client\src\actions\profileActions.js:48:14
45 | axios
46 | .post("/api/profile", profileData)
47 | .then(res => history.push("/dashboard"))
> 48 | .catch(err =>
| ^ 49 | dispatch({
50 | type: GET_ERRORS,
51 | payload: err.response.data
答案 0 :(得分:0)
然后的问题是,只有主机返回响应,但不在err.response
状态码范围内时,axios的2xx
对象才会存在。
如果主机在返回响应之前出错,或者初始请求存在问题,则err.response
属性将不存在,因此err.response.data
将引发异常。
处理错误的最彻底方法将是axios docs中的类似内容……
.catch(function (error) {
const errorMessage = (()=> {
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);
return error.response.data;
} 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);
return error.request;
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
return error.message;
}
})();
dispatch({
type: GET_ERRORS,
payload: errorMessage
})
});