javascript 我怎么知道我得到了401错误时提取数据?

cbjzeqam  于 2023-03-11  发布在  Java
关注(0)|答案(1)|浏览(109)

我使用异步函数来获取数据,我怎么知道我得到了401错误时,获取数据?
代码如下:

async function getBilling(url, id, date) {
        let header = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`,
            },
        }
        const response = await fetch(`${url}/billing/${id}/${date}`, header)
        const data = await response.json()

        if (data.code === 0) {
            // setState(...)...
        } else {
            // ...
        }
    }

当令牌过期时,我会在浏览器控制台上看到此错误
CORS策略已阻止从源“http://localhost:3000”在“http://...”进行提取的访问:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需要,请将请求的模式设置为“no-cors”以在禁用CORS的情况下提取资源。
获取http://.../2022年10月网络::错误_失败401
未捕获(承诺中)TypeError:无法获取...
即使我加上这一行

...
    const response = await fetch(`${url}/billing/${id}/${date}`, header)
    if (!response.ok) {
            **console.log(response.status)**
            throw new Error(`HTTP error! status: ${response.status}`)
    }
    ...

在浏览器开发模式下,控制台标记中仍无法显示。
所以问题是我怎么知道我得到了401错误?
谢谢你。

u0sqgete

u0sqgete1#

请考虑使用try/catch胶囊。

async function getBilling(url, id, date) {
  try {
    let header = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`
      }
    };
    const response = await fetch(`${url}/billing/${id}/${date}`, header);
    const data = await response.json();

    // setState(...)...
  } catch (error) {
    console.log(error);
  }
}

在catch部分,您将获得所有可能的错误。

} catch (error) {
    console.log(error);
    // Handle all actions when the endpoint has failed. 
  }

请阅读更多关于try/catch胶囊here的信息

相关问题