我用的是react router dom 6.22.3
我创造了browser router
个这样的
{
path: "/",
element: <MainLayout />,
errorElement: <Error />,
children: [
{
path: "/",
element: <Dashboard />,
loader: DashbaordLoader,
errorElement: <Error />,
},
]
}
在Dashboard
组件中,我正在获取数据.
export const DashbaordLoader = async () => {
try {
const data = await fetcher("http://localhost:3000/users", "GET");
return data;
} catch (err) {
throw err;
}
};
fetcher
只是javascript
取数函数
export const fetcher = async (url: string, method: string) => {
try {
const response = await fetch(url, {
method,
headers: {
"Content-Type": "application/json",
Authorization: "",
},
});
return response.json()
} catch (err) {
throw err;
}
};
如您所见,没有Authorization
令牌,因此服务器的响应如下所示
状态代码为401
在身体里{error: 'Need to login'}
但这件事是在dashboardLoader
美元之内.即使数据是statusCode 401
它不会进入catch block
分.当响应为401
时,如何使其显示错误元素
以下是postman
中的错误响应