javascript - Express 不为 React 重定向

标签 javascript reactjs express

我正在使用 React 并通过 GET 请求将 req.params.id 发送到我的 express 后端。如果成功,它会发送 JSON。如果不是,它应该重定向到某个 URL。但它没有发送重定向请求来使用react?当我在 Postman 中测试它时,当我将它换成 res.status(401).json({unauthorized: you don't have authority to view this});

有什么建议吗?

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'
            }));
    })
});

最佳答案

重定向功能将您重定向到节点 js 应用程序内的新路由。您应该向您的 React 应用程序返回一条信息,例如:

if (score.user.toString() !== req.user.id && req.user.role !== 'admin') {
        return res.status(403).send({ error: "not-authorized" });
} else {
        res.json(score);
}

然后您可以在您的 React 应用程序中处理它,并使该应用程序将您重定向到正确的路线。

关于javascript - Express 不为 React 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56283863/

相关文章:

javascript - 为什么这个被屏蔽的 JS 代码在 GET 参数 : '*alert(13)*' executed on my page?

javascript - 获取选择器中的第一个和最后一个对象

javascript - 如何以正确的顺序显示月份?

javascript - Node js优化回调函数和nodemailer?

node.js - 将我的应用程序(node、express、mongo)与本地数据库连接并查询

javascript - iframe DOM 覆盖

javascript - onFocus 和 onBlur 不会在 React 中渲染

javascript - 为什么表单输入未定义?

javascript - 类型错误 : Cannot read property 'style' of null in React App

javascript - 使用默认路由的 Express.js 路由