如何在不付费的情况下保护用户访问的路径?

时间:2020-12-22 06:57:25

标签: reactjs

我有一个向客户收费的系统。每次成功付款后,我都会使用

将他们带到收据页面 <块引用>

history.push('/receipt/:orderid')

现在我想知道如何保护它?我不会让用户在不付款的情况下从结帐页面访问它,例如 xyz.com/receipt/321。目前,任何登录用户都可以输入 URL 并访问它。

3 个答案:

答案 0 :(得分:0)

您可以使用 react-router-guards npm 包,它为 React Router 提供了一个中间件 API,允许您在导航调用和路线的最终渲染。

$ npm install react-router-guards

答案 1 :(得分:0)

您可以将受保护的路由包装在另一个 React 组件中。 让我们将此组件命名为 ProtectedRoutes,以便现在我们可以深入研究代码。

ProtectedRoutes.js

import React, { useContext, useState, useEffect } from "react";

export function ProtectedRoutes({ children, location }) {
  useEffect(() => {
    //this is where you send a request to the server to check if the user has made the payment
    //and if the response was false redirect the user using history.replace()
  }, [location.pathname])
  return (
    <div>
      {children}
    </div>
  );
}

Router.js

<ProtectedRoutes>
  <Route path="/product" exact component={Product} />
</ProtectedRoutes>

通过使用这个概念,您可以轻松保护您的路线。

答案 2 :(得分:0)

我建议:在订单页面,检查token,如果用户有权限,发送数据给用户。

相关问题