【发布时间】: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 时,它会记录任何内容吗?