【发布时间】:2023-01-25 22:39:17
【问题描述】:
我正在开发 React 和 Node 应用程序,但我不明白如何将从后端给出的错误传递到前端获取中的 catch 块。
login 函数使用 fetch,如果服务器返回 not-ok 状态则抛出错误。服务器还返回我需要在前端显示的错误数组。
我的问题是,当强制错误并将错误抛出到 fetch promise 的 catch 块中时,我无法将后端返回的错误数组提供给 catch。 我将响应提供给 catch,当它被记录时,它说它是一个对象 Response。而且它没有来自后端响应的错误属性。
这是前端的登录功能:
function handleLogin() {
fetch('http://localhost:5000/auth/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
})
.then((response) => {
if(!response.ok) {
throw Error(response)
}
return response.json()
})
.then((token) => {
localStorage.setItem('token', token);
history.push('/');
window.location.reload();
})
.catch((error) => {
console.log('error: ', error); // error: Error: [object Response]
console.log('error:', error.errors); // undefined
setErrors(error.errors)
})
}
这是后端登录的控制器:
exports.login = async (req, res) => {
const { password, username } = req.body;
const hasErrors = validationResult(req);
// VALIDATE INPUTS
if (!hasErrors.isEmpty()) {
console.log('there are errros')
return res.status(401).json({
erros: hasErrors.array(),
});
}
// VALIDATE USER
const user = await User.findOne({ username });
if (!user) {
return res.status(401).send({
erros: [
{
msg: 'Invalid Credentials 1',
},
],
});
}
const isValid = await bcrypt.compare(password, user.password);
if (isValid) {
// SIGN THE JWT
const token = await JWT.sign({ username }, 'mysecret', {
expiresIn: 864_000,
});
return res.json(token);
} else {
return res.status(401).send({
erros: [
{
msg: 'Could not save the user into the db',
},
],
});
}
}
【问题讨论】: