Logout request from Javascript to Flask

I’m trying to logout user from my web application using Flask-Login.

Here’s my Javascript function:

function logout() {
  var req = new XMLHttpRequest();
  req.open("POST", "http://myaddress/logout", true);
  req.withCredentials = true;
  req.send();

Here’s my Python function:

@app.route('/logout')
@login_required
def logout_function():
    logout_user() # Built-in Flask-Login function
    return app.send_static_file('login.html')

When I send my request from Javascript I receive 200, but the page remains still, because redirect doesn’t happen. I tried changing the last line of Python function to return redirect(url_for('login_function')), but it didn’t help.

Could it be my Javascript function that causes the problem?

7 thoughts on “Logout request from Javascript to Flask”

  1. You need to redirect to the logout page using JavaScript:

    function logout() {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
               window.location.replace("http://myaddress/logout.html");
            }
        };
        req.open("POST", "http://myaddress/logout", true);
        req.withCredentials = true;
        req.send();
    }
    

    You can hardcode the logout-URL like shown above. In this case you just need to return a 200 status code:

    return ('', 200)
    

    If you want to return the url, you can access it with req.responseText:

    Flask:

    return (url_for('login_function'), 200)
    

    JavaScript:

    if (this.readyState == 4 && this.status == 200) {
        window.location.replace(req.responseText);
    }
    
    Reply

Leave a Comment