[英]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.