Firefox 似乎是唯一在执行此同步请求时不会抛出错误的浏览器,知道为什么吗?
// Make sure to have your JS console open when you run this
var url = '//api.soundcloud.com/resolve.json?url=http://soundcloud.com/matas/hobnotropic&client_id=83f67039ae0c3790030d256cb9029678';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false); // SYNCHRONOUS
xhr.onload = alert.bind(null, 'Loaded');
xhr.send(null);
执行几乎相同的异步 XMLHttpRequest 不会导致任何错误,并且请求会按预期完成:
// Make sure to have your JS console open when you run this
var url = '//api.soundcloud.com/resolve.json?url=http://soundcloud.com/matas/hobnotropic&client_id=83f67039ae0c3790030d256cb9029678';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true); // ASYNCHRONOUS
xhr.onload = alert.bind(null, 'Loaded');
xhr.send(null);
据我所知:
- SoundCloud API返回正确的 CORS header 。
- SoundCloud resolve API执行到
http://api.soundcloud.com/tracks/49931.json
的 302 重定向。 - 如果请求是异步执行的,它将成功遵循重定向并完成。
- 如果请求是同步执行的,那么它将失败并在控制台中显示以下错误(没有 Firefox):
- Chrome:“NetworkError:发生网络错误。”
- Opera:“NetworkError:发生网络错误。”
- Safari:“XMLHttpRequest 异常 101:同步请求中发生网络错误。”
谁能解释为什么同步请求失败?以及为什么它会因如此奇怪的错误而失败,尤其是因为异步执行时相同的请求有效?为什么该参数会有所不同?这是 Firefox 或 WebKit/Blink 人群的已知错误吗?
编辑:我有opened a new issue on Chrome's bug tracker因为还没有人能够在规范中指出任何可以正确解释这种行为的内容。当我有机会时,我可能会为 WebKit 打开一个类似的问题。
最佳答案
这似乎是为了阻止使用同步请求而故意做出的选择:
- w3 网络应用邮件列表:Disable new response types for sync XHR in Window context
- w3 错误:Investigate if synchronous XHR in window context should not support new XHR responseTypes
- Webkit:Synchronous XHR in window context should not support new XHR responseTypes for HTTP(S) requests
- Mozilla:Investigate if synchronous XHR in window context should not support new XHR responseTypes
据我所知,IE 似乎从一开始就不支持它。
关于javascript - 同步 CORS XHR 302 重定向失败,但异步工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20224883/