Q:

(Ajax & express js) Express js authorize middleware

I have a simple middleware of authorize in my app. It works perfectly in both GET and POST normal requests but when i make a POST request via ajax, It doesn't redirect to a page 401 instead it ignores the middleware and continues to my model and insert data into the db.
Code:
function(req, res, next){
        if(!req.session.user){
            res.status(401);
            res.redirect('/401');
        }
        next(); }

Can someone explain me why this middleware isn't working if it is an ajax request but working correctly with normal requests?

A:

The problem is that even though you are sending a redirect, the javascript code execution continues because next() is not inside an else clause. So putting a return right after res.redirect('/401') or putting next() inside an else will avoid the problem.

