Buc*_*x55 1 javascript express reactjs
我正在使用React并通过GET请求将req.params.id发送到我的快速后端。如果成功,则发送JSON。如果不是,它应该重定向到某个URL。但这不是发送该重定向请求来做出反应吗?当我在Postman中进行测试时,将其换成res.status(401).json({未授权:您无权查看此}}),它可以正常工作。
有什么建议么?
router.get('/score/:id', passport.authenticate('jwt', {
session: false
}), (req, res) => {
User.findOne({
user: req.user.id
})
.then(user => {
Scores.findById(req.params.id)
.then(score => {
// Check for score owner to prevent anyone from accessing score
if (score.user.toString() !== req.user.id && req.user.role !== 'admin') {
return res.redirect('/not-authorized');
} else {
res.json(score);
}
})
.catch(err => res.status(404).json({
scorenotfound: 'Score not found'
}));
})
});
Run Code Online (Sandbox Code Playgroud)
小智 5
重定向功能可将您重定向到节点js应用程序内的新路由。您应该将以下信息返回给您的react app:
if (score.user.toString() !== req.user.id && req.user.role !== 'admin') {
return res.status(403).send({ error: "not-authorized" });
} else {
res.json(score);
}
Run Code Online (Sandbox Code Playgroud)
然后您可以在react应用中处理它,并使该应用将您重定向到正确的路线。