You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Create a Global Axios Instance
    Make a new file in your project (like src/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;
    
  2. 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);
      }
    };
    
Using Native Fetch (No Third-Party Libraries)

If you prefer sticking to native Fetch without Axios, you can wrap it in a custom function that automatically adds your headers:

  1. Wrap Fetch in a Global Function
    Create a file like src/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;
    
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:14:52