React中如何向API传递JWT Token并处理请求结果
Fixing Your React JWT-Fetch Component
Hey there! Let's get your component working exactly how you need it. I'll go through the gaps in your current code and add all the missing functionality to handle the button click, JWT transmission, success/error states, and UI feedback.
First, let's list out the key issues we need to address:
- Missing state variables for
address, error messages, and the login form fields (email/password) - Undefined
customFetchfunction that your button is trying to call - Case mismatch with
Axios(you imported lowercaseaxios, so we need to use that consistently) - No logic to retrieve the stored JWT from cookies when making the API call
- No error handling for failed requests
- No UI to display error messages like "认证失败"
Here's the complete, fixed component with explanations:
import axios from 'axios'; import React, { useState } from 'react'; import { Button } from '@material-ui/core'; // Helper function to get cookies by name (since you're using setCookie, we need this to retrieve the token) const getCookie = (name) => { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); }; // Make sure your setCookie function is defined (add this if you haven't already) const setCookie = (name, value) => { document.cookie = `${name}=${value}; path=/`; }; function TestPage() { // State for login form fields const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); // State for API response and errors const [address, setAddress] = useState(''); const [error, setError] = useState(''); // Login function to get JWT and store it const onLogin = () => { const variables = { email, password }; axios.post('/auth/login', variables) .then((res) => { // Store token and expiry in cookies setCookie('token', res.payload.accessToken); setCookie('exp', res.payload.accessTokenExpiresIn); // Set default auth header for future axios requests axios.defaults.headers.common['Authorization'] = `Bearer ${res.payload.accessToken}`; // Fetch user info (optional, as per your original code) return axios.get('/user/me'); }) .then((res) => { console.log('User info:', res); // Clear any previous errors after successful login setError(''); }) .catch((err) => { console.error('Login failed:', err); setError('登录失败,请检查账号密码'); }); }; // The customFetch function your button will call const customFetch = (e) => { e.preventDefault(); // Clear previous state before making a new request setAddress(''); setError(''); // Retrieve the stored JWT from cookies const token = getCookie('token'); if (!token) { setError('请先登录获取认证令牌'); return; } // Make the API call with the JWT in the Authorization header axios.get('/your-address-api-endpoint', { // Replace with your actual API route headers: { Authorization: `Bearer ${token}` } }) .then((res) => { // Update state with the returned address (adjust based on your API's response structure) setAddress(res.data.address); }) .catch((err) => { console.error('Request failed:', err); // Set error message for authentication failure setError('认证失败'); }); }; return ( <> {/* Optional: Login form for testing */} <div style={{ marginBottom: '20px' }}> <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} style={{ marginRight: '10px', padding: '4px' }} /> <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} style={{ marginRight: '10px', padding: '4px' }} /> <Button variant="contained" color="secondary" onClick={onLogin}> 登录 </Button> </div> {/* Address fetch button */} <div> <Button variant="contained" color="primary" style={{ width: '200px' }} onClick={customFetch} > 获取地址 </Button> </div> {/* Display address or error messages */} {address && <div style={{ marginTop: '10px', fontSize: '16px' }}>返回的地址:{address}</div>} {error && <div style={{ marginTop: '10px', color: 'red', fontSize: '16px' }}>{error}</div>} </> ); } export default TestPage;
Key Changes Explained:
- Cookie Helpers: Added
getCookieto retrieve the stored JWT, andsetCookie(since your original code referenced it but didn't define it). - State Management: Added state for login fields, the returned address, and error messages to keep track of UI state changes.
customFetchImplementation:- Clears stale state before each request to avoid confusing feedback
- Checks for a valid token first (shows an error if the user isn't logged in)
- Attaches the JWT to the API request's
Authorizationheader - Updates the address state on success, or sets the "认证失败" error on failure
- Error Handling: Added
.catch()blocks to both login and address requests to catch failures and show user-friendly messages. - UI Polish: Added a basic login form for testing, and styled the address/error messages for better readability.
Don't forget to replace /your-address-api-endpoint with the actual backend route that returns the address you need.
内容的提问来源于stack exchange,提问作者user17713066
相关产品推荐
相关产品推荐

