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

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

问题描述

我想知道在使用ajax函数时我们应该如何从后端处理400。我们可以使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.

请注意 上的MDN页面> fetch()


成功获取fetch()的准确检查包括检查
的promise是否已解决,然后检查Response.ok属性是否为
a值为true。 HTTP状态404不构成网络
错误。

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(function(response) {
         if (!response.ok) {
             // create error object and reject if not a 2xx response code
             var 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天全站免登陆