Node Express项目前端JWT存储及请求携带实现咨询
Hey there! I totally get where you're coming from—most tutorials do skip over the frontend implementation details for JWT auth, but it's actually pretty straightforward once you see concrete examples. Let's break this down step by step for your Node/Express/PostgreSQL stack.
1. How to Fetch and Store the JWT Token on the Frontend
First, you'll send a login request to your backend (with user credentials like email/password). If the credentials are valid, your backend should respond with the JWT token in the JSON payload. Here's how to capture that token and store it in localStorage:
Example with Fetch API
async function handleLogin(email, password) { try { // Send login request to your backend endpoint const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email, password }) }); const responseData = await response.json(); if (response.ok) { // Extract the token from the backend's response (adjust the key based on your backend's output) const jwtToken = responseData.token; // Store the token in localStorage localStorage.setItem('jwtAuthToken', jwtToken); console.log('Token saved successfully!'); // Redirect to dashboard or protected page here window.location.href = '/dashboard'; return true; } else { console.error('Login failed:', responseData.message); return false; } } catch (error) { console.error('Request error:', error); return false; } }
Example with Axios
If you're using Axios (a popular HTTP client), the process is similar:
async function handleLogin(email, password) { try { const response = await axios.post('/api/login', { email, password }); const jwtToken = response.data.token; localStorage.setItem('jwtAuthToken', jwtToken); console.log('Token saved successfully!'); window.location.href = '/dashboard'; return true; } catch (error) { console.error('Login failed:', error.response.data.message); return false; } }
Note: The key name (jwtAuthToken) can be anything you want—just be consistent when retrieving it later.
2. How to Attach the Token to Authenticated Requests
Once the token is stored, you need to include it in the Authorization header of every request that requires authentication. The standard format is Bearer <your-token>.
Example with Fetch API
async function fetchUserProfile() { try { // Retrieve the token from localStorage const jwtToken = localStorage.getItem('jwtAuthToken'); if (!jwtToken) { console.error('No token found—please log in first'); window.location.href = '/login'; return; } const response = await fetch('/api/user/profile', { method: 'GET', headers: { 'Authorization': `Bearer ${jwtToken}`, // Critical: Attach the token here 'Content-Type': 'application/json' } }); const userData = await response.json(); if (response.ok) { console.log('User profile:', userData); return userData; } else { console.error('Failed to fetch profile:', userData.message); // If token is expired/invalid, clear it and redirect to login if (response.status === 401) { localStorage.removeItem('jwtAuthToken'); window.location.href = '/login'; } } } catch (error) { console.error('Request error:', error); } }
Example with Axios (Using Interceptors for Convenience)
Axios lets you set up request interceptors to automatically attach the token to every request, so you don't have to manually add the header each time:
// Create a dedicated Axios instance for authenticated requests const authAxios = axios.create({ baseURL: '/api', headers: { 'Content-Type': 'application/json' } }); // Add a request interceptor to inject the token authAxios.interceptors.request.use( (config) => { const jwtToken = localStorage.getItem('jwtAuthToken'); if (jwtToken) { config.headers.Authorization = `Bearer ${jwtToken}`; } return config; }, (error) => { return Promise.reject(error); } ); // Now use this instance for protected requests async function fetchUserProfile() { try { const response = await authAxios.get('/user/profile'); console.log('User profile:', response.data); return response.data; } catch (error) { console.error('Failed to fetch profile:', error.response.data.message); if (error.response.status === 401) { localStorage.removeItem('jwtAuthToken'); window.location.href = '/login'; } } }
Quick Security Note
localStorage is convenient but vulnerable to XSS attacks. If your app requires high security, consider using HttpOnly cookies to store the token (this requires backend configuration for cookie settings and CORS). For most standard applications though, localStorage is a widely accepted choice.
内容的提问来源于stack exchange,提问作者Juan Francisco Carías Álvarez

