如何在Fetch API中处理HTTP代码4xx响应

Art*_*rek 4 javascript fetch promise

我想知道使用ajax函数时如何从后端处理400。我们可以在promise resolve函数中创建if语句,并检查res状态是否为400。不同的方法是为包装程序提供获取服务,当我们从服务器获取400时,将引发异常。该如何处理?

Ism*_*ilS 9

这样我们就可以相应地处理所有类型的状态。

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 });
  }
})
Run Code Online (Sandbox Code Playgroud)

灵感


jfr*_*d00 5

我建议使用包装器检查response.ok响应代码为2xx时是否为true。

请在MDN页面上fetch()注意以下语句:

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

这是一个这样的包装器:

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;
    });
}
Run Code Online (Sandbox Code Playgroud)