如何在 fetch api 中处理 HTTP 代码 4xx 响应 [英] How to handle HTTP code 4xx responses in fetch api

查看:24
本文介绍了如何在 fetch api 中处理 HTTP 代码 4xx 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当我们使用ajax函数时我们应该如何处理来自后端的400.我们可以在promise解析函数中创建if语句并检查res状态是否为400.不同的方法是为fetch创建包装服务,当我们从服务器获取400时我们抛出异常.如何处理这个问题?

I was wondering how we should handle 400 from backend when we use ajax function. We can make if statement in promise resolve function and check if res status is 400. Different approach is making wrapper service for fetch, and when we got 400 from server we throw exception. How to deal with that problem ?

推荐答案

我建议使用一个包装器来检查 response.ok 如果响应代码是 2xx,这将是 true.

I'd suggest a wrapper that checks response.ok which will be true if the response code is 2xx.

请注意来自 fetch 上的 MDN 页面的此声明():

Note this statement from the MDN page on fetch():

对成功 fetch() 的准确检查将包括检查承诺已解决,然后检查 Response.ok 属性是否具有值为真.404 的 HTTP 状态不构成网络错误.

An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true. An HTTP status of 404 does not constitute a network error.

这是一个这样的包装器:

Here is a wrapper like this:

function fetchData() {
    return fetch.apply(null, arguments).then(response => {
         if (!response.ok) {
             // create error object and reject if not a 2xx response code
             let err = new Error("HTTP status code: " + response.status)
             err.response = response
             err.status = response.status
             throw err
         }
         return response
    })
}

这篇关于如何在 fetch api 中处理 HTTP 代码 4xx 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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