【问题标题】:Cannot read property 'error' of undefined. What's the problem?无法读取未定义的属性“错误”。有什么问题?
【发布时间】:2019-05-17 05:46:03
【问题描述】:

我的 REST API 原因如下:{"error":"Auth failed. User does not exist"}。 我尝试在 React 中使用 setState 将此错误保存到我的状态,但我有一个错误:无法读取未定义的属性“错误”。有什么问题?

export const login = user =>
  axios
    .post('http://localhost:3000/api/users/login', {
      login: user.login,
      password: user.password,
    })
    .then(res => {
      localStorage.setItem('userToken', res.data.token);
      return res.data.token;
    })
    .catch(err => {
      console.log(err);
    });

React.js 中的函数:

  onSubmit(e) {
    e.preventDefault();

    const user = {
      login: this.state.login,
      password: this.state.password,
    };

    login(user).then(res => {
      if (!res.error) { // <- this error: TypeError: Cannot read property 'error' of undefined
        this.props.history.push(`/dashboard`);
      } else {
        this.setState({ error: res.error });
      }
    });
  }

这是我的后端代码:

    // Login Action
...
              return res.status(200).json({
                message: 'Auth successful',
                token,
              });
            }
            res
              .status(400)
              .json({ error: 'Auth failed. The password is incorrect.' });
          } else {
            res.status(400).json({ error: 'Auth failed. User does not exist' });
          }
        })
        .catch(err => {
          res.status(400).json({ error: err });
        });
    };

【问题讨论】:

  • 使用console.log(res)查看后端实际返回的响应,然后你可以告诉响应的结构,看看错误是否可能是res.data.error之类的别的。这种方式在 res 对象属性错误不存在。
  • 我的第一个猜测是,如果您有错误,您不会在 catch 块中返回任何内容?所以也许在你的catch块中添加return error会解决它编辑:cannot read property of undefined意味着你的res是未定义的,所以这可能是你必须从catch块返回一些东西的原因
  • 您好,方法 login 与 React.js 中的方法在同一个文件中?最简单的方法是在捕获错误时直接设置状态: .catch(err => { console.log(err); });
  • @RomainLeQllc 我编辑了我的帖子并添加了控制器代码。
  • 我的意思是你的login函数中的catch块,你有一个console.log(err)。当您进入 catch case 时,它​​会记录任何内容吗?

标签: node.js reactjs rest api


【解决方案1】:

试试这个:

login(user).then(() => this.props.history.push(`/dashboard`))
.catch(error=>this.setState({ error })

但也许还有另一个问题,您通常不能出于不变性考虑而强制说明您的方式。我想你知道,但我发帖以防万一:

this.setState({ history: [...this.state.history, `/dashboard`] })

【讨论】:

    【解决方案2】:

    由于您的后端返回带有 400 状态码的响应,因此您必须在登录函数的 catch 块中处理它。现在您正在将错误写入控制台并且没有返回任何内容,这就是您的登录响应在 React 代码中未定义并且您收到该错误的原因。 要解决此问题,请更改登录功能的 catch 块,使其看起来像这样

     .catch(err => {
        console.log(err);
        return {error:err};
    });
    

    【讨论】:

      【解决方案3】:

      试试这个;

      export const login = user =>
      axios
      .post('http://localhost:3000/api/users/login', {
        login: user.login,
        password: user.password,
      })
      .then(res => {
        localStorage.setItem('userToken', res.data.token);
      })
      .then(() => return localStorage.getItem('userToken');)
      .catch(err => {
        console.log(err);
      });
      

      【讨论】:

      • 仍然显示未定义的错误?你有没有尝试过我刚刚编辑的这种方式?
      猜你喜欢
      • 2019-06-14
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 2022-01-03
      • 2022-01-01
      • 2020-10-15
      相关资源
      最近更新 更多