Chrome cancels CORS XHR upon HTTP 302 redirect

試著忘記壹切 提交于 2019-11-27 00:55:43

The answers in here are mixed, hinting on certain settings in code etc. which may solve the redirect problem with CORS, but the CORS spec clearly specifies when such CORS redirects will fail/pass : As per the spec, browsers should

  1. Allows 3XX redirect , if the request to the redirected resource doesn't require pre-flight check (simple CORS requests without custom header for example). See https://www.w3.org/TR/cors/#simple-cross-origin-request-0

If the manual redirect flag is unset and the response has an HTTP status code of 301, 302, 303, 307, or 308 Apply the redirect steps

  1. Don't allow 3XX redirect, if the request to redirected resource requires pre-flight check. See https://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0

If the response has an HTTP status code of 301, 302, 303, 307, or 308 Apply the cache and network error steps.

I have explored various CORS scenarios in github repo: https://github.com/monmohan/cors-experiment.

This specific issue with failed redirect can also be easily reproduced in isolation by the bundle here: https://github.com/monmohan/cors-experiment/tree/master/issue

http://httpstatus.es/302

If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Josh Rosenblum

I found this post about setting the correct Access-Control-Allow-Origin CORS header on your 302 response to be helpful, at least in my similar-sounding case.

Investigation of the problem showed that his XHR was not landing on the CORS-enabled URL directly, but was being redirected to it through an HTTP 302 (redirect) response.

So bear in mind that the redirecting URL must also include an Access-Control-Allow-Origin header, else the browser will stop right there with its attempted cross-domain request.

I've also found that setting additional CORS headers above and beyond Access-Control-Allow-Origin will often result in a cancelled transaction.

Ronald

I also had the problem that Chrome was not following a redirect on a CORS request. For me the problem was that the JS-framework I use (Sencha Touch) adds a request header: X-Requested-With: "XMLHttpRequest"

As soon as I removed this (in Sencha Touch by calling Ext.Ajax.setUseDefaultXhrHeader(false);) it worked like a charm.

Not sure why but I hope this information helps someone.

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