json - 无法在 React 应用程序中访问来自 Express 服务器的响应数据

标签 json node.js reactjs express redux

在我的 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/

相关文章:

javascript - 如何将二维复选框名称解析为具有匹配索引的 JSON?

python - 是否有用于 Python 的 Gson 类似库

node.js - Jade 和 NodeJs,有什么好的教程吗?

javascript - 如何模拟 jest/enzyme 测试的 css 导入?

reactjs - 在react-redux中分派(dispatch)2个同步操作时,状态不会在第一个操作上更新

jquery - 使用基本 json 获取 twitter api

java - 如何使用 HashMap 填充 MySQL 数据库

macos - Socket.io:如何处理关闭连接?

node.js - 使用 Grunt 调试连接/缩小文件

javascript - onClick 和 event.target 不工作 react