Ajax with 302 response code testing

  • 2020-03-26 21:32:50
  • OfStack

In an ajax request, if the server-side response is 302 Found, can the status code be retrieved in the ajax callback function? Can I get the value of Location from Response Headers for a redirect? Let's take a look at the actual situation.
The javascript code to make an ajax request using jquery's $.ajax() is as follows:

    url: '/oauth/respond',
    type: 'post',
    data: data,
    complete: function(jqXHR){
    error: function (xhr) {

When the server returns the response 302 Found, the browser runs as follows:
< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201310/23141637-b50fb17b68ba48c9bd3157d2a86adf6d.png? 2013923155646 ">  

The status code in the ajax complete() and error() callbacks is 404 instead of 302.

Why is that?

It's on stackoverflow

You can't handle redirects with XHR callbacks because the browser takes care of them automatically. You will only get back what at the redirected location.

It turns out that when the server sends the 302 Response to the browser, the browser does not directly handle the ajax callback. Instead, the browser first performs the 302 redirect -- reads the Location information from the Response Headers, then sends a request to the Url in the Location, and then handles the ajax callback after receiving the Response to the request. The general process is as follows:
Jax - > Browser - > Server - > 302 - > Browser (redirect) - > Server - > Browser - > The ajax callback
In our test program, the redirect URL returned by 302 has no corresponding handler on the server, so we get a 404 status code in the ajax callback function. If there is a corresponding URL, the status code is 200.
So, if you want to redirect via location.href based on the 302 response in an ajax request, it's not feasible.

How to solve it?

Methods a
Continuing with ajax, modify the server-side code to change the original 302 response to a json response, as shown in the ASP.NET MVC sample code below:

return Json(new { status = 302, location = "/oauth/respond" });

Ajax code can be slightly modified:

    url: '/oauth/respond',
    type: 'post',
    data: data,
    dataType: 'json',
    success: function (data) {
        if (data.status == 302) {
            location.href = data.location;

Method 2
Instead of using ajax, use forms.

<form method="post" action="/oauth/respond">

I haven't studied this problem before, so I stepped into the pit several times. After this study, I think I will get away from this pit in the future.

Related articles: