Chaining Express.js 4's res.status(401) to a redirect

后端 未结 3 2023
长发绾君心
长发绾君心 2020-12-14 20:00

I\'d like to send a response code of 401 if the requesting user is not authenticated, but I\'d also like to redirect when the request was an HTML request. I\'ve been finding

3条回答
  •  天涯浪人
    2020-12-14 20:50

    I fell on the same issue and decided to use the session to handle this kind of job.

    I didn't want to have an intermediate view...

    With the below code, I can redirect to the homepage, which will be rendered with 401 unauthorized code.

    app.get('patternForbiddenRoute', (req, res, next) => {
           // previousCode
           if (notForbidden === true) {
               return res.render("a_view");
           }
    
           req.session.httpCode = 401;
    
           res.redirect('patternHomeRoute');
    });
    
    app.get('patternHomeRoute', (req, res, next) => {
           res.render("my_home_view", {}, (error, html) => {
                // ... handle error code ...
    
                const httpCode = req.session.httpCode;
                if (httpCode !== undefined) {
                    delete req.session.httpCode;
                    res.status(httpCode);
                }
    
                res.send(html);
           }));
    });
    

提交回复
热议问题