【发布时间】:2019-11-11 00:25:55
【问题描述】:
我不知道发生了什么。当我尝试向后端发送请求以添加追随者(我的路线如下)时,我得到服务器 tiemout 错误而不是成功,但在我的数据库中,追随者被正确添加(并删除),但并非总是如此。有时它会保存 3 次相同的结果(关注者到 db),或者有时不会删除关注者。 问题是我不知道发生了什么。
在我的控制台中,有时我会看到此错误: [HPM] 尝试将请求 /api/users/user/follow 从 127.0.0.1:8080 代理到 http://[::1]:1648 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors) 时出错
setFollower 路线:
const setFollowing = async (req, res, next) => {
try {
const userId = req.body.userId;
const followId = req.body.followId;
await User.findByIdAndUpdate(
userId,
{
$push: {
following: followId,
},
},
);
next();
} catch (err) {
res.status(400).json({
error: err,
});
}
};
const setFollower = async (req: Request, res: Response) => {
try {
const followId = req.body.followId;
const userId = req.body.userId;
const result = await User.findByIdAndUpdate(
followId,
{
$push: {
followers: userId,
},
},
{ new: true },
)
.populate('following', '_id name')
.populate('followers', '_id name')
const followerResult = { ...result._doc };
const { photo, salt, passwordHash, ...rest } = followerResult;
return res.status({ ...rest });
} catch (err) {
res.status(400).json({
error: err,
});
}
};
router.put(
'/user/follow',
isUserSignIn,
setFollowing,
setFollower,
);
点击按钮发送请求
try {
setLoading(true);
const response = await fetch('/api/users/user/follow', {
body: JSON.stringify({
followId: params.userId,
userId: loggedInUser._id,
}),
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
method: 'PUT',
});
const data = await response.json();
setLoading(false);
setFollowing(true);
} catch (err) {
if (err.message) {
setServerError(err.message);
} else {
setServerError(JSON.stringify(err));
}
}
【问题讨论】: