简体   繁体   中英

Native ajax call does not redirect on 302

I have been googling for hours now. I've read a dozen "answers" on Stackoverflow, all of them using jQuery.

This is the common answer...

The ajax-request will follow that redirect afaik

Well, it doesn't.

I am trying to send a PUT from a form via native JS AJAX

[Please I beg you, don't tell me to use jQuery. I found a bug in jQuery via PUT ( 1 ) so I'm going around it]

This is my code snippet...

  var xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.send(data);
  xhr.onload = function (e) {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        console.log(xhr.responseText);
      } else {
        console.error(xhr.statusText);
      }
    }
  };
  xhr.onerror = function (e) {
    console.error(xhr.statusText);
  };

This block works great, I can POST, PUT and DELETE without issues. The server receives the data and updates the DB according to the sent METHOD just fine.

My (SLIM based) PHP, upon successful completion, returns a 302 and a URL to go to.

This process works using POSTMAN hitting the PHP, and it goes to the right page.

Opening Chrome Tools/Network, it shows that the PHP is returning a 302 and than a 200

My response object contains the full HTML for a page in the responseText property.

Funny thing is, if I hard code a bad URL,the browser goes to my 404 page fine.

Your thoughts? (Please don't ask me or tell me to use jQuery)

EDIT/ADDENDUM -----------------------

I have discovered that the redirect is using the same METHOD of the original call.

I'm doing

 PUT /user/1

the Redirect is doing

 PUT http://myserver.test/

This is the right place to go. Now I understand the 405.

I don't have a PUT route defined, therefore the 405.

I create a PUT route and it works in POSTMAN but still gives me a 405 in Chrome and Firefox.

I have 2 issues to solve: 1) change the METHOD on the redirect 2) figure out why the browser doesn't like the 307

I found "a" solution. I'm not sure I like it, but...

  var xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.send(data);
  xhr.onload = function (e) {
    if (xhr.readyState === 4) {
        window.location.replace(xhr.responseURL);  // <---- solution
    }
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM