繁体   English   中英

如何在 fetch api 中处理 HTTP 代码 4xx 响应

[英]How to handle HTTP code 4xx responses in fetch api

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

我建议使用一个检查response.ok的包装器,如果响应代码为 2xx,这将是正确的。

请注意fetch()上 MDN 页面中的此语句:

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

这是一个这样的包装器:

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(url, {
  method: 'POST',
  headers: headers,
  body: JSON.stringify({ user_email: email }),
}).then((response) => {
  return new Promise((resolve) => response.json()
    .then((json) => resolve({
      status: response.status,
      ok: response.ok,
      json,
    })));
}).then(({ status, json, ok }) => {
  const message = json.message;
  let color = 'black';
  switch (status) {
    case 400:
      color = 'red';
      break;
    case 201:
    case 200:
      color = 'grey';
      break;
    case 500:
    default:
      handleUnexpected({ status, json, ok });
  }
})

灵感

我为此找到的最佳方法是将其包装在一个新的 Promise 中,如果response.ok为 false,则拒绝带有错误上下文的 Promise。

/**
 * Parses the JSON returned by a network request
 *
 * @param  {object} response A response from a network request
 *
 * @return {object}          The parsed JSON, status from the response
 */
function parseJSON(response) {
  return new Promise((resolve) => response.json()
    .then((json) => resolve({
      status: response.status,
      ok: response.ok,
      json,
    })));
}

/**
 * Requests a URL, returning a promise
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 *
 * @return {Promise}           The request promise
 */
export default function request(url, options) {
  return new Promise((resolve, reject) => {
    fetch(endpoint  + url, options)
      .then(parseJSON)
      .then((response) => {
        if (response.ok) {
          return resolve(response.json);
        }
        // extract the error from the server's json
        return reject(response.json.meta.error);
      })
      .catch((error) => reject({
        networkError: error.message,
      }));
  });
}

(在https://github.com/github/fetch/issues/203上发表评论)

将它合并到您的 HTTP 抽象中可能是一个好主意。 也许有某种options参数:

const myFetch = (method, path, {headers, strictErrors, whatever}) => {
  // fetch here, if strictErrors is true, reject on error.
  // return a Promise.
}

myFetch('GET', 'somepath', {strictErrors: true})
  .then(response => {})
  .catch(err => { /* maybe 400 */ });

fetch的包装通常是一个好主意, fetch是一个相对较低级别的函数。 就像在任何地方直接创建新的 XHR 对象不是一个好主意一样,我相信在应用程序的各个部分直接调用fetch()也不是一个好主意。 在某些方面,它类似于全局变量。

暂无
暂无

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

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