【问题标题】:Best way to check status code of http response?检查http响应状态码的最佳方法?
【发布时间】:2020-08-10 20:08:30
【问题描述】:

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

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

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

});

但是,语句有幻数。例如200 或 400。 是否有避免幻数的最佳做法?

【问题讨论】:

  • 它们不是神奇的数字,它们是HTTP response status codes
  • 您可以将它们定义为常量以使它们更具可读性,但这些常量将保存“幻数”,尽管它们是已定义和标准化的 API 接口。
  • 感谢您的回复。我知道它是定义的代码。但是当我开发后端服务时,我总是使用库来将 http.StatusOK 设置为 200。在 if 语句中使用数字不利于长期发展。
  • 浏览器是否有内置的状态码定义库?这是很常见的用法。我认为为每个开发人员维护一个并不好。

标签: javascript


【解决方案1】:

状态码是响应对象的状态属性。此外,除非您在错误响应中使用 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();
});

【讨论】:

    猜你喜欢
    • 2010-10-12
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 2012-08-05
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多