carboncomputed
carboncomputed

Reputation: 1620

Why wont this request follow my Tornado redirect?

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.js"></script>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align"="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form)
{
    $.ajax({
    type: 'POST',
    url: '/auth/login',
    data: { 
        'UserName': form.userid.value, 
        'Password': form.pswrd.value // <-- the $ sign in the parameter name seems unusual, I would avoid it
    },
    success: function(msg){
       console.log(msg);
    }
});
}
</script>
</body>
</html>

Tornado code: class MainHandler(BaseHandler): @tornado.web.authenticated def get(self): self.render("index.html")

class AuthLoginHandler(BaseHandler):
    @tornado.web.asynchronous
    def get(self):
        self.render("login.html")

    def post(self):
        username = self.get_argument("UserName",strip = True)
        password = self.get_argument("Password",strip = True)
        user = auth_actions.do_login(db,username,password)
        if not user:
            raise tornado.web.HTTPError(500, "Authentication Failed")
        self.set_secure_cookie("user", tornado.escape.json_encode(user))
        self.redirect("/")

I send the redirect request and instead of the browser redirecting it just gets the html data of index.html in msg.

Upvotes: 2

Views: 3294

Answers (1)

Death
Death

Reputation: 2017

You're using AJAX to retrieve a page, not a command.

Imagine you have a webpage open, then you want to get data from another page. You open that page in a new tab, and the server-side tells it to redirect to "/", so you find yourself at index.html in this second tab, but the first one remains in the same location.

This is exactly what your AJAX is doing. You've told it to get the contents of the page, and when that page sends a redirect order, it just gets the contents of the page the request is redirected to and returns that instead.

Due to this, AJAX returns a 200 status code for success, instead of a 301 code for a redirect. What would be a better solution, is to have your server reply with unique response, which the browser can recognise and redirect appropriately. An example of this could be to output a simple string, such as redirect, which would never appear on its own in a valid output. The jQuery could then be altered appropriately:

success: function(msg){
   if (msg=='redirect') {
      //Redirect to the index
   }
   else {
      console.log(msg);
   }
}

This would redirect if appropriate, or output to the log otherwise.

Upvotes: 4

Related Questions