当您在开发环境中测试React应用程序时通常不需要进行身份验证,但是在生产环境中可能需要进行身份验证。当您在生产环境中尝试访问需要身份验证的API时,系统返回401响应代码。 这种问题的解决办法是在您的React应用程序中添加正确的身份验证信息,例如使用JWT令牌身份验证机制。
以下是使用JWT令牌进行身份验证的示例代码:
import axios from 'axios'; import jwt_decode from 'jwt-decode';
const API_URL = process.env.REACT_APP_API_URL;
const login = async (username, password) => { const response = await axios.post(API_URL + 'auth/login', { username: username, password: password }); if (response.data.accessToken) { localStorage.setItem('user', JSON.stringify(response.data)); } return response.data; };
const logout = () => { localStorage.removeItem('user'); };
const getCurrentUser = () => { const user = JSON.parse(localStorage.getItem('user')); if (user && user.accessToken) { const decodedToken = jwt_decode(user.accessToken); const currentTime = Math.floor(Date.now() / 1000); if (decodedToken.exp < currentTime) { logout(); window.location.reload(); } return user; } else { return null; } };
export default { login, logout, getCurrentUser };
在此示例中,我们定义了三个函数:login、logout和getCurrentUser。login函数采用用户名和密码作为参数,并与后端API进行通信以获取JWT令牌。如果响应中包含JWT令牌,则将该令牌存储在本地存储中以便后续使用。logout函数仅从本地存储中删除用户信息。getCurrentUser函数返回当前用户的信息。如果用户没有登录,该函数返回null。如果用户已登录,则我们使用jwt-de