When using React with Axios to make requests, there are several common ways to include the JWT token. A common approach is to add the token to the request headers. Below are the specific steps and code examples:
Step 1: Install Axios
If you haven't installed Axios yet, you can install it using npm or yarn:
bashnpm install axios
or
bashyarn add axios
Step 2: Create an Axios Instance and Configure Default Headers
We can create an Axios instance and configure its default settings, such as the API base URL and headers. This approach ensures that the token is automatically included in every request without needing to set it repeatedly.
javascriptimport axios from 'axios'; const API = axios.create({ baseURL: 'https://api.example.com/', headers: { 'Content-Type': 'application/json' } }); const token = 'your_jwt_token'; if (token) { API.defaults.headers.common['Authorization'] = `Bearer ${token}`; }
Step 3: Use the Axios Instance to Make Requests
Now, every time you use this Axios instance to make a request, the JWT token will automatically be included in the Authorization header of the HTTP request.
javascriptAPI.get('/endpoint') .then(response => { console.log('Data:', response.data); }) .catch(error => { console.error('Error:', error); });
Step 4: Refresh Token
In some scenarios, the JWT token may expire. We can handle token expiration using Axios interceptors, for example, automatically refreshing the token and re-sending the request.
javascriptAPI.interceptors.response.use( response => response, error => { const originalRequest = error.config; if (error.response.status === 401 && !originalRequest._retry) { originalRequest._retry = true; // Assume there is a function to refresh the token return refreshToken().then(res => { if (res.status === 200) { API.defaults.headers.common['Authorization'] = `Bearer ${res.data.token}`; return API(originalRequest); } }); } return Promise.reject(error); } );
Example Summary
The above demonstrates how to use the Axios library in a React application to include the JWT token in requests. By configuring the default settings of the Axios instance, we can easily manage and use HTTP request headers, which is particularly helpful for maintaining large applications. Additionally, interceptors can handle complex scenarios such as token refresh, making the user authentication flow smoother.