![](/img/trans.png)
[英]How can I redirect a /:user link to 404 page in react redux
[英]How do I redirect to error page after receiving status 404 from API call in React?
我有一個帶有參數adminId
的簽入頁面,它將調用 API 來檢查帳戶是否存在。 由於我使用的是 React Router,我可以在參數上設置任何值,它仍然會呈現頁面。 問題是,如果adminId
未經過驗證,我不想呈現頁面,並且想將其重定向到 homepage/404 頁面。
下面是代碼。
簽入頁面中的 API 請求
const { adminId } = useParams();
const checkAccount = async () => {
const fetchAccount = await axios
.post(`/auth/form/${adminId}`, {
validateStatus: () => true,
})
.then((res) => {
if (res.status === 404) {
window.location.href = "/";
return;
}
console.log(res.status);
});
};
路由.js
function Routes() {
return (
<Switch>
<RouteRegistration path="/" component={SignIn} exact />
<RouteRegistration path="/signup" component={CreateAccount} exact />
<Route path="/checkin/:adminId" component={CheckIn} exact />
<RouteProtected path="/dashboard" component={Dashboard} exact />
{/* <Route path="/dashboard" component={Dashboard} exact /> */}
<Route component={Error} />
</Switch>
);
}
const RouteRegistration = ({ component: Component, ...rest }) => {
const { auth } = useContext(AuthApi);
return (
<Route
{...rest}
render={(props) =>
!auth ? (
<Component {...props} />
) : (
// <Redirect to={`/dashboard/${adminId}`} />
<Redirect to="/dashboard" />
)
}
/>
);
};
const RouteProtected = ({ component: Component, ...rest }) => {
const { auth } = useContext(AuthApi);
return (
<Route
{...rest}
render={(props) =>
auth ? <Component {...props} /> : <Redirect to="/" />
}
/>
);
};
export default Routes;
Api代碼
router.post("/form/:adminId", (req, res) => {
const adminId = req.params.adminId;
User.find({ adminId: adminId })
.exec()
.then((docs) => {
const response = {
usersinfo: docs.map((doc) => {
return {
auth: true,
message: "Account verified",
};
}),
};
if (docs.length > 0) {
res.status(200).json(response);
} else {
res.status(404).json({
message: "No entries found",
});
}
})
.catch((err) => {
console.log(err);
res.status(500).json({
error: err,
});
});
});
您可以使用
history.push("/")
或者
history.push("/404")
此外,如果您的狀態代碼不是 200,您將不會在 then 回調的響應中收到它。 要捕獲錯誤,您可以像這樣使用 catch:
const fetchAccount = await axios
.post(`/auth/form/${adminId}`, {
validateStatus: () => true,
})
.then(res => history.push("/404")).catch(err => console.log(err));
我使用下面的代碼解決了這個問題
const checkAccount = async () => {
const fetchAccount = await axios
.post(`/auth/form/${adminId}`, {
validateStatus: () => true,
})
.catch((err) => {
console.log(err.response.status);
if (err.response.status === 404) {
window.location.href = "/";
return;
}
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.