如何将Node登录注册系统与React Todo应用整合,实现权限控制
Hey there! Let's walk through how to integrate your Node.js login/register app with your React Todo app, so users have to authenticate before accessing any Todo features. I'll break this down into actionable steps and share some best practices:
Your Node app will act as the backend API—it handles user registration, login, and secures all Todo-related operations. Your React app will be the frontend client that sends requests to the Node API, stores the user's authentication token, and restricts access to Todo pages until the user logs in.
First, let's make sure your Node app is ready to support authenticated Todo requests:
- Add JWT (JSON Web Token) support: When a user logs in successfully, return a signed JWT token containing user details (use packages like
jsonwebtokenfor this). - Create an auth middleware: Write a reusable middleware function that checks for a valid JWT token in incoming requests. This middleware will protect your Todo API endpoints (like
/api/todos,/api/todos/add, etc.).
Example middleware code:const jwt = require('jsonwebtoken'); const authenticateToken = (req, res, next) => { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; // Extracts "Bearer <token>" if (!token) return res.sendStatus(401); // Unauthorized if no token jwt.verify(token, process.env.JWT_SECRET, (err, user) => { if (err) return res.sendStatus(403); // Forbidden if token is invalid req.user = user; next(); // Proceed to the protected route }); }; // Use this middleware for Todo routes: app.get('/api/todos', authenticateToken, (req, res) => { // Fetch todos for req.user.id from your database }); - Update Todo endpoints: Modify your Todo API to fetch/save todos linked to the authenticated user (using the user ID from the decoded JWT).
- Ensure password security: Double-check that you're hashing passwords with
bcryptbefore storing them in your database (never store plain text passwords!).
Now let's update your React app to handle authentication and route protection:
- Install a HTTP client: Use
axios(or the built-infetch) to send requests to your Node API.axiosis great because it lets you set up request interceptors to automatically add the auth token to every request. - Store the auth token: After a successful login, save the JWT token to
localStorage(orsessionStorageif you want the token to expire when the browser closes). You can also use React Context or Redux to manage the user's auth state globally.
Example login handler:import axios from 'axios'; const handleLogin = async (email, password) => { try { const response = await axios.post('/api/login', { email, password }); const token = response.data.token; localStorage.setItem('authToken', token); // Redirect to Todo page after login window.location.href = '/todos'; } catch (error) { alert('Invalid credentials!'); } }; - Add route protection: Use React Router to create a
PrivateRoutecomponent that checks if the user has a valid token before allowing access to the Todo page.
Example PrivateRoute:import { Navigate } from 'react-router-dom'; const PrivateRoute = ({ children }) => { const token = localStorage.getItem('authToken'); return token ? children : <Navigate to="/login" />; }; // Use it in your router: <Routes> <Route path="/login" element={<LoginPage />} /> <Route path="/register" element={<RegisterPage />} /> <Route path="/todos" element={<PrivateRoute><TodoApp /></PrivateRoute>} /> </Routes> - Auto-add token to API requests: Set up an axios interceptor to include the auth token in every request to your Node API:
axios.interceptors.request.use((config) => { const token = localStorage.getItem('authToken'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }); - Update Todo components: Replace any local Todo storage logic with API calls to your Node backend (e.g., fetch todos with
axios.get('/api/todos'), add a todo withaxios.post('/api/todos/add', { text: newTodo })).
- Handle token expiration: Add logic to catch 401/403 errors from the backend (which mean the token is invalid/expired). Clear the token from storage and redirect the user to the login page.
- Use React Context for auth state: Instead of checking
localStorageeverywhere, create anAuthContextto hold the user's login state and token. This makes it easier to manage and update state across components. - Secure your API: Use HTTPS in production to prevent token interception. You can also set CORS policies in your Node app to only allow requests from your React app's domain.
- Add logout functionality: Create a logout button that removes the token from
localStorageand redirects to the login page.
That should cover all the basics! Let me know if you run into specific issues with any part of the setup.
内容的提问来源于stack exchange,提问作者Mohsin

