Axios 是否具有检测重定向的能力?

Does Axios have the ability to detect redirects?

Response interface of the Fetch API has a read-only flagredirected,指示响应是否是重定向请求的结果。

axios 库是否有类似的功能?我能找到的最好的是 maxRedirects,它设置了要遵循的最大重定向数。但是,我只是想确定它是否发生(因此我可以专门处理重定向),而不是阻止它发生。

将代码中的请求 URL 与 response.request.[=10= 给出的 URL 进行比较];如果它们不相等,你就知道请求被重定向了。

至于状态码是200,那是规范要求的;浏览器中的前端 JavaScript 运行 不会暴露任何中间状态代码——无论您使用哪个 API。另请参阅

中的答案

您可以获得重定向计数:

const response = await axios.get('http://someurlthatredirects.com');
console.log(response.request._redirectable._redirectCount);

我试图访问 Axios 中请求对象中的响应 sub-object,文档中将其描述为

// `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {}

我不太明白这是什么意思,所以@ori888 的评论对 response.request.res.responseUrl 有效,现在我可以将客户端重定向到该地址,而且它有效 谢谢 ori888