乐闻世界logo
搜索文章和话题

How to pass Header JWT Token with Axios in React?

1个答案

1

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:

bash
npm install axios

or

bash
yarn 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.

javascript
import 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.

javascript
API.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.

javascript
API.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.

2024年6月29日 12:07 回复

你的答案