收到404时获取失败,无法加载资源

时间:2018-08-22 13:19:03

标签: javascript fetch

我有一种方法可以从API提取数据,但是在收到错误响应时会记录错误(404、500)。

如果状态为错误,我只想返回“ undefined”作为数据,这是我的错误,如何清除控制台上的错误?

fetch.js

export default (url, method, authorization, body) => {
    const headers = { 'Content-Type': 'application/json' }
    if (authorization) headers.Authorization = localStorage.getItem('id_token');
    return fetch(url, {
        method,
        headers,
        body: JSON.stringify(body)
    }).then(res => res.ok ? res.json() : undefined)
    .catch(console.log);
}

控制台

console errors

来源

sources

2 个答案:

答案 0 :(得分:1)

每次添加.catch()时,如果有错误,代码都会转到该位置,然后跳过(res)=>部分。

因此,如果您想摆脱控制台的错误,可以:

export default (url, method, authorization, body) => {
    const headers = { 'Content-Type': 'application/json' }
    if (authorization) headers.Authorization = localStorage.getItem('id_token');
    return fetch(url, {
        method,
        headers,
        body: JSON.stringify(body)
    }).then(res => res.ok ? res.json(console.log(res)) : undefined) // check the result directly
}

答案 1 :(得分:1)

我认为,当任何请求返回4XX或5XX范围内的HTTP错误代码时,Chrome总是会在控制台中显示错误,对此您无能为力。

catch未被触发的原因是,当您在then(或catch)中返回内容时,则使承诺链回到成功模式。如果要将其置于失败模式并触发下一个catch,则需要专门返回被拒绝的Promise:

尝试以下方法:

export default (url, method, authorization, body) => {
  const headers = { 'Content-Type': 'application/json' }
  if (authorization) headers.Authorization = localStorage.getItem('id_token')
  return fetch(url, {
    method,
    headers,
    body: JSON.stringify(body),
  })
    .then(res => {
      res.ok ? res.json() : Promise.reject(undefined)
    })
    .catch(console.log)
}
相关问题