简体   繁体   中英

How do I redirect to error page after receiving status 404 from API call in React?

I have a checkin page with a params adminId which will call an API to check the existence of the account. Since I'm using React Router, I can put any value on the params and it will still render the page. The problem is, I don't want to render the page if the adminId is not verified and would like to redirect it to the homepage/404 page.

Below are the codes.

API request in CheckIn Page

 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);
      });
  };

Routes.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 code

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,
      });
    });
});

You can use

history.push("/")

OR

history.push("/404")

Also if your status code is anything other than 200, you will not receive it in response of the then callback. To catch errors, you use catch like this:

const fetchAccount = await axios
  .post(`/auth/form/${adminId}`, {
    validateStatus: () => true,
  })
  .then(res => history.push("/404")).catch(err => console.log(err));

I solved the problem using the codes below

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;
        }
      });
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM