Мой REST API объясняет это: {"error":"Auth failed. User does not exist"}
.Я пытаюсь сохранить эту ошибку в моем состоянии, используя setState в React, но у меня есть эта ошибка: Не удается прочитать свойство 'error' из undefined.В чем проблема?
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 });
});
};