【问题标题】:Can not access response data from express server in React app无法从 React 应用程序中的快速服务器访问响应数据
【发布时间】:2017-06-10 12:37:25
【问题描述】:

在我的 React 应用程序中,我试图访问从这段服务器代码返回的错误。

  User.findByUsername(req.body.username)
    .then((foundUsername) => {
      if (foundUsername) {
        return res.status(422)
          .json({
            error: 'This username is not available.'
          });
      }

这是客户端的动作创建者

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 登录到控制台,这就是我得到的结果

错误:请求失败,状态码 422 在 createError (eval at 150 (bundle.e3597bf….js:39), :15:15) 结算时(eval at 258 (bundle.e3597bf….js:125), :18:12) 在 XMLHttpRequest.handleLoad (eval at 147 (bundle.e3597bf….js:7), :77:7)

then 中记录res 给了我想要的对象。任何帮助将不胜感激。

【问题讨论】:

  • 字段 { displayName, email, password, username } 是否正确?可能不是${API_URL}/signup/?需要令牌授权吗?

标签: json node.js reactjs express redux


【解决方案1】:

res 对象中有两个键。

configresponse

您要查找的错误消息在res.response.data.error

【讨论】:

  • 谢谢!得到它的工作。我猜我很困惑,因为我可以在成功案例中直接访问res.data
猜你喜欢
  • 2022-01-21
  • 2018-10-04
  • 2021-09-24
  • 2021-12-15
  • 2019-06-27
  • 2020-11-17
  • 1970-01-01
  • 2014-12-14
  • 1970-01-01
相关资源
最近更新 更多