繁体   English   中英

检查 http 响应状态码的最佳方法?

[英]Best way to check status code of http response?

问题是:得到 http 响应时检查状态码的最佳方法是什么? 例如

fetch('https://stackoverflow.com/').then((response)=>{
    if (response.status >= 400) {
        //handle unsuccessful request ...
    }

    // or 
    if (response.status == 200) { 
        // status ok 
    }

});

然而,这些陈述有神奇的数字。 例如 200 或 400。是否有避免幻数的最佳做法?

状态码是响应 object 上的状态属性。 此外,除非您在错误响应中使用 JSON(当然有些人会这样做),否则您需要在调用 json 之前检查状态代码(或 ok 标志):

fetch('https://jsonplaceholder.typicode.com/todos/1').then((response)=>{
    console.log(response.status); // Will show you the status
    if (!response.ok) {
        throw new Error("HTTP status " + response.status);
    }
    return response.json();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM