我试图在我的项目中实现JWT,有一篇文章提供了一个很好的解决方案:
https://dev.to/sanjayttg/jwt-authentication-in-react-with-react-router-1d03.
Routes.jsx
import { RouterProvider, createBrowserRouter } from "react-router-dom";
import { useAuth } from "../provider/authProvider";
import { ProtectedRoute } from "./ProtectedRoute";
import Login from "../pages/Login";
import Logout from "../pages/Logout";
const Routes = () => {
const { token } = useAuth();
// Define public routes accessible to all users
const routesForPublic = [
{
path: "/service",
element: <div>Service Page</div>,
},
{
path: "/about-us",
element: <div>About Us</div>,
},
];
// Define routes accessible only to authenticated users
const routesForAuthenticatedOnly = [
{
path: "/",
element: <ProtectedRoute />, // Wrap the component in ProtectedRoute
children: [
{
path: "",
element: <div>User Home Page</div>,
},
{
path: "/profile",
element: <div>User Profile</div>,
},
{
path: "/logout",
element: <Logout/>,
},
],
},
];
// Define routes accessible only to non-authenticated users
const routesForNotAuthenticatedOnly = [
{
path: "/",
element: <div>Home Page</div>,
},
{
path: "/login",
element: <Login/>,
},
];
// Combine and conditionally include routes based on authentication status
const router = createBrowserRouter([
...routesForPublic,
...(!token ? routesForNotAuthenticatedOnly : []),
...routesForAuthenticatedOnly,
]);
// Provide the router configuration using RouterProvider
return <RouterProvider router={router} />;
};
export default Routes;
ProtectedRoute.jsx
import { Navigate, Outlet } from "react-router-dom";
import { useAuth } from "../provider/authProvider";
export const ProtectedRoute = () => {
const { token } = useAuth();
// Check if the user is authenticated
if (!token) {
// If not authenticated, redirect to the login page
return <Navigate to="/login" />;
}
// If authenticated, render the child routes
return <Outlet />;
};
Github: https://github.com/sanjay-arya/react-auth-demo
我基本上创建了一个Auth上下文,为所有路由提供令牌信息,并允许访问路由,无论用户是否有令牌.它也有一个登录和注销系统删除/创建令牌.
提供的代码运行良好,因为它是.当我想在注销后将用户重定向到"/login"
页而不是"/"
页时,就会出现问题.我把Logout.jsx中的navigate("/", { replace: true })
改为navigate("/login", { replace: true });
.
我得到了这个错误:
react-router-dom.js?v=7652cf65:202 Uncaught Error: Could not find a matching route for errors on route IDs: 2
at invariant (react-router-dom.js?v=7652cf65:202:11)
at _renderMatches (react-router-dom.js?v=7652cf65:3167:33)
at useRoutesImpl (react-router-dom.js?v=7652cf65:3033:25)
at DataRoutes (react-router-dom.js?v=7652cf65:3422:10)
at renderWithHooks (react-dom_client.js?v=7652cf65:12171:26)
at updateFunctionComponent (react-dom_client.js?v=7652cf65:14577:28)
at beginWork (react-dom_client.js?v=7652cf65:15912:22)
at HTMLUnknownElement.callCallback2 (react-dom_client.js?v=7652cf65:3674:22)
at Object.invokeGuardedCallbackDev (react-dom_client.js?v=7652cf65:3699:24)
at invokeGuardedCallback (react-dom_client.js?v=7652cf65:3733:39)
Show 19 more frames
console.js:213 The above error occurred in the <DataRoutes> component:
at DataRoutes (http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=7652cf65:3419:5)
at Router (http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=7652cf65:3491:15)
at RouterProvider (http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=7652cf65:3375:5)
at Routes (http://localhost:5173/src/routes/index.jsx?t=1712483351401:26:7)
at AuthProvider (http://localhost:5173/src/provider/authProvider.jsx:21:3)
at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
这是一个未捕获的错误,但即使添加errorElement到路由,错误仍然存在.即使如此,我仍然不知道为什么会出现错误.我已经想了好几个小时了,但没有成功.