我如何确定提取请求的状态码? [英] How do I determine the status code of a Fetch request?

查看:101
本文介绍了我如何确定提取请求的状态码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个URL并确定它的状态码,尤其是它有一个HTTP 301或HTTP 302状态码:

  fetch('https://httpstat.us/301',{
redirect:'true'})
.then(response => {
console.log响应);
const headers = response.headers.entries();
(h的头文件){
console.log(h);
}
} ).catch(err => {
console.log(in error case)
console.log(err);
})



这给了我很多信息,特别是它告诉我:

  response.redirected 

这是真的。但是这只告诉我它重定向了,而不是状态码。



有没有一种方法可以使用Fetch API来确定请求的真实状态码?

解决方案

确定第一个回答你的问题否,你不能确定301和302之间没有后端变化的区别。这个 SO dicussion 为后端解决方案)。

您可以做的另一件事是将重定向设置为'错误',在这种情况下,fetch会在所有重定向上抛出错误,并且您可以处理如果是重定向,会发生什么。



这种情况的主要原因是(从我的理解中)是因为301和302之间的区别主要对浏览器有用它需要处理后续请求应该如何表现(是否永久更改缓存或只是这个请求)。

但是就用户而言,规范指定了要处理的两种情况透明地表示你需要知道有重定向,但是状态码是什么sed重定向并不重要。因此只有response.redirected标志。但是,如果您仍然需要请遵循上述后端解决方案。


I want to fetch an URL and determine what status code it has, especially if it has an HTTP 301 or HTTP 302 status code:

fetch('https://httpstat.us/301', {
    redirect: 'true'})
    .then(response => {
       console.log(response);
       const headers = response.headers.entries();
       for (h of headers) {
        console.log(h);
        }
    }).catch(err => {
        console.log("in error case")
        console.log(err);
    })

This does give me a lot of information, especially it tells me via:

response.redirected 

Which is true. But this only tells me that it redirected, not what the status code was.

Is there a way to use Fetch API to determine the real status code of the request?

解决方案

OK first to answer your question no you cannot determine the difference between 301 and 302 without some changes in the backend.(Follow this SO dicussion for backend solution).

The other thing you can do is to set redirect to 'error' in which cases fetch will throw an error on all redirects and you can handle what happens if it was a redirect.

The main reason why this is like that is (from my understanding) is because the difference between 301 and 302 is mainly useful to browsers which needs to handle how subsequent request should behave (whether to permanently change the cache or just this request).

But in terms of the user the spec specifies both cases to handled transparently meaning you need to know there is a redirect but what status code caused the redirect does not matter. Hence only the response.redirected flag. But if you still need to please follow the above backend solution.

这篇关于我如何确定提取请求的状态码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆