[英]Browser not redirecting to URL
我有一个 API 返回 302 状态代码和目标位置。 但是当我从我的 angular 代码调用这个 API 时,浏览器没有重定向到目标 URL。 相反,它使用 XHR 调用目标 URL(这是一个 HTML 页面)并给出如下错误:
error: SyntaxError: Unexpected token < in JSON at position 0 at Object.parse () at XMLHttpRequest.onLoad text: "\n
基本上它尝试将 HTML 响应解析为 JSON 并失败。 那么如何让浏览器重定向到目标 URL 而不是将其称为 XHR。
浏览器不会跳转到 XHR 302 响应的 header 返回的Location
。 如果你想让浏览器重定向,你应该自己做。
这是代码:
const url = 'http://your-api.com'
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
// This means our request undergoes a redirection
if (xhr.responseURL !== url) {
window.location = xhr.responseURL
}
else {
// Do something else, like JSON.parse(xhr.responseText)
}
}
}
xhr.open('GET', url)
xhr.send()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.