在我的 React 应用程序中,我试图访问从这段服务器代码返回的错误。
User.findByUsername(req.body.username)
.then((foundUsername) => {
if (foundUsername) {
return res.status(422)
.json({
error: 'This username is not available.'
});
}
这是客户端的 Action 创建者
export const signupUser = ({ displayName, email, password, username }) => {
return (dispatch) => {
axios.post(`${API_URL}/signup`, { displayName, email, password, username })
.then((res) => {
dispatch({ type: AUTH_USER });
localStorage.setItem('token', res.data.token);
browserHistory.push('/');
})
.catch((res) => {
console.log(res.data.error);
});
};
};
我似乎无法弄清楚的是,我可以在 then
情况下访问 res.data.token
,但在 catch
情况下无法获取 res.data.error
,即使我可以在 chrome 的网络选项卡中看到响应。
这就是我在 catch
案例中将 res
记录到控制台时得到的结果
Error: Request failed with status code 422 at createError (eval at 150 (bundle.e3597bf….js:39), :15:15) at settle (eval at 258 (bundle.e3597bf….js:125), :18:12) at XMLHttpRequest.handleLoad (eval at 147 (bundle.e3597bf….js:7), :77:7)
在 then
中记录 res
给了我想要的对象。任何帮助将不胜感激。
最佳答案
res 对象中有两个键。
配置
和响应
您要查找的错误消息位于 res.response.data.error
关于json - 无法在 React 应用程序中访问来自 Express 服务器的响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41849772/