How to catch an expected (and intended) 302 Ajax response?

北战南征 提交于 2019-12-10 15:49:52

问题


So, if you look back at my previous question about Exchange Autodiscover, you'll see that the easiet way to get the autodiscover URL is to send a non-secure, non-authenticated GET request to the server, ala:

http://autodiscover.exchangeserver.org/autodiscover/autodiscover.xml

The server will respond with a 302 redirect with the correct url in the Location header.

I'm trying out something really simple at first with a Chrome extension, where I have:

if (req.readyState==4 && req.status==302) {
    return req.getResponseHeader("Location");
}

With another ajax call set up with the full XML Post and the user credentials,

But instead Chrome hangs at this point, and a look at the developer panel shows that it is not returning back the response but instead is acting like no response was given, meanwhile showing a

Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101

in the error log.

The way I see it, refering to the exact response status is about the same as "catching" it, but I'm not sure if the problem is with Chrome/WebKit or if this is how XHR requests always handle redirects.

I'm not sure how to catch this so that I can get still get the headers from the response.

Or would it be possible to set up a secondary XHR such that when it gets the 302, it sends a totally different request?

Quick Update

I just changed it so that it doesn't check the response code:

if (req.readyState==4) {
    return req.getResponseHeader("Location");
}

and instead when I alert out the value it's null. and there is still the same error and no response in the dev console. SO it seems like it either doesn't track 302 responses as responses, or something happens after that wipes that response out?


回答1:


See the w3c docs on xhr: the XHR will either transparently follow the redirect or return a network error (like what you're seeing from Chrome), depending on whether the redirect's destination is in the same origin as the original request. So your code really doesn't have a chance to catch the 302 response at all. That's why the "Location" response header is unset: at this point, you're inspecting the headers of the final response, not the 302 response.



来源:https://stackoverflow.com/questions/2770289/how-to-catch-an-expected-and-intended-302-ajax-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!