用于检查用户是否在 Node.js 重定向中通过身份验证的中间件

Middleware to Check if a User is Authenticated in Node.js redirect

成功登录后,我在 Node express server 中为用户提供 60 分钟的身份验证会话。如果我的 react app 中的用户想要获取子列表,我必须检查已验证,这里我有问题,我执行 axios 请求 get 并在我的文件 app.js(node) 中执行:

app.get('/childrenList', isUserLoggedIn, function(req, res, next){
    children.getChildrenList(req, res, next);
    });

我的函数是 UserLoggedIn

function isUserLoggedIn(req, res, next) {
    if (!req.session.user_id || typeof(req.session.user_id)==='undefined') {      
        res.redirect('/login');            
        }
    else{
        next();
        }
    }

我的redux/actions函数

export function childrenList(objSql,type){
    return {
        type: type,
        payload: new Promise((resolve, reject)=>{
            axios.get('/childrenList', objSql,{
            })
            .then(function(response) {
                resolve(response);
                });
            })
        }
    }

如果用户刷新页面(重定向到 '/login'),Eveythign 工作正常,但如果用户在会话过期后仅单击按钮 "Get childrens",则节点不会重定向到页面 '/login'。我如何在 session expired 之后重定向?

因为您无法使用服务器重定向从 React 进行重定向。 看到这个 .

你必须在客户端处理它。在服务器响应中,抛出错误或发送正确的响应 "unauthenticated"。在 axios 响应中,检查响应。如果响应是 "unauthenticated",请清除您的 session/local 存储并将其重定向到“/login”。