ReactJS中如何全局注入user-id、auth自定义HTTP请求头(类Angular方式)
Hey there! Great question—adding global request headers in React is totally achievable, even if it doesn’t have Angular’s built-in interceptor system out of the box. Let’s walk through the two most common approaches based on which HTTP client you’re using:
Axios has a built-in interceptor mechanism that works almost like Angular’s HTTP interceptors, making it the easiest way to add global headers:
Create a Global Axios Instance
Make a new file in your project (likesrc/utils/axiosInstance.js) to initialize Axios and set up the request interceptor:import axios from 'axios'; // Create a custom Axios instance with your base API URL const axiosInstance = axios.create({ baseURL: 'https://your-api-base-url.com', }); // Add a request interceptor to inject headers before sending requests axiosInstance.interceptors.request.use( (config) => { // Grab user-id and auth from localStorage (or your state manager) const userId = localStorage.getItem('user-id'); const authToken = localStorage.getItem('auth'); // Add headers if the values exist if (userId) { config.headers['user-id'] = userId; } if (authToken) { config.headers['auth'] = authToken; } return config; }, (error) => { // Handle request errors here return Promise.reject(error); } ); export default axiosInstance;Use This Instance in Your Components
Instead of using the global Axios object everywhere, import your custom instance for all API calls:import axiosInstance from '../utils/axiosInstance'; const fetchData = async () => { try { const response = await axiosInstance.get('/api/data'); console.log(response.data); } catch (error) { console.error('Request failed:', error); } };
If you prefer sticking to native Fetch without Axios, you can wrap it in a custom function that automatically adds your headers:
Wrap Fetch in a Global Function
Create a file likesrc/utils/fetchWithHeaders.js:const fetchWithHeaders = async (url, options = {}) => { // Get user-id and auth values const userId = localStorage.getItem('user-id'); const authToken = localStorage.getItem('auth'); // Merge custom headers with any passed-in headers const headers = { ...options.headers, 'Content-Type': 'application/json', // Adjust based on your API needs }; // Add headers if values exist if (userId) { headers['user-id'] = userId; } if (authToken) { headers['auth'] = authToken; } // Send the request with the combined headers const response = await fetch(url, { ...options, headers, }); // Optional: Handle non-success responses globally if (!response.ok) { throw new Error(`Request failed with status: ${response.status}`); } return response; }; export default fetchWithHeaders;Use the Wrapped Fetch in Components
Import your custom fetch function whenever you need to make an API call:import fetchWithHeaders from '../utils/fetchWithHeaders'; const fetchData = async () => { try { const response = await fetchWithHeaders('https://your-api-base-url.com/api/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Request failed:', error); } };
Bonus: Pulling Values from State Management
If your user-id and auth are stored in a state manager like Redux or Zustand, just grab them from there instead of localStorage. For example, with Zustand:
import useAuthStore from '../stores/authStore'; // Inside your interceptor or wrapped fetch function const { userId, authToken } = useAuthStore.getState();
内容的提问来源于stack exchange,提问作者kulls

