在我的 React 应用程序中,我正在我的
useEffect
中进行简单的获取。
useEffect(() => {
async function fetchData() {
const res = await fetch(
"https://api-production.afghantell.com/apiv1/eligibilities",
);
console.log(res.status);
console.log(res.headers);
}
fetchData();
}, []);
当响应成功时,一切都很好。但是当请求失败时,例如出现 400 错误,我无法访问
res
,即使使用 try catch 块也没有任何帮助。此失败的获取响应中有一个特定的 X-reason
属性,我需要访问该属性,但无法访问。
您正在尝试在 useEffect 中发出 http 请求。 您已经定义了一个异步 fetchData() 函数来执行请求。但是,您在代码中使用了await find()。 不是处理异步请求中错误的正确方法。
useEffect(() => {
async function fetchData() {
try {
const res = await fetch("https://api-production.afghantell.com/apiv1/elegibilidades");
if (!res.ok) {
throw new Error("Error en la solicitud: " + res.status);
}
const data = await res.json();
console.log(data.estado);
console.log(res.headers);
} catch (error) {
console.error("Error en la solicitud:", error);
//Here you can access the "message" attribute of the error for specific details.
}
}
fetchData();
}, []);
fetch() 执行请求 如果响应不成功(状态代码不是 200),它会抛出错误并提供响应状态的详细信息。 然后。 在 catch 块中,访问错误的 message 属性以获取有关错误的信息