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

如何通过Axios拦截器自动发送当前URL?

实现方案

方案一:Axios请求拦截器 + window.location(推荐)

这是最直接可靠的实现方式,利用Axios的请求拦截器,在每次发起请求时自动获取当前浏览器的完整URL并添加到请求头中,完全不需要客户端手动处理。

代码示例

首先创建全局Axios实例并配置拦截器:

import axios from 'axios';

// 创建Axios实例
const api = axios.create({
  baseURL: '/api' // 替换为你的后端接口基础路径
});

// 添加请求拦截器,自动注入当前URL到请求头
api.interceptors.request.use(config => {
  // 获取当前页面的完整URL
  const currentFullUrl = window.location.href;
  // 自定义请求头(和后端约定好字段名,比如X-Source-URL)
  config.headers['X-Source-URL'] = currentFullUrl;
  return config;
}, error => {
  return Promise.reject(error);
});

export default api;

在React组件中直接导入使用:

import api from './path/to/your/api-instance';

function UserDashboard() {
  const fetchUserInfo = async () => {
    try {
      const response = await api.get('/user/profile');
      // 处理接口响应
    } catch (err) {
      // 处理请求错误
    }
  };

  return <button onClick={fetchUserInfo}>获取用户信息</button>;
}

可靠性说明

每次请求触发时,拦截器都会实时读取window.location.href,无论React路由切换、页面刷新还是浏览器前进后退,都能拿到准确的当前页面URL,完全规避了referrer头因浏览器策略、跨域请求或请求方式导致的不可靠问题。

方案二:结合React Router的上下文提供者(适用于需精确路由路径场景)

如果后端只需要React路由的路径部分(比如/dashboard/user而非完整域名URL),可以通过React上下文维护当前路由路径,再注入到Axios请求头中。

代码示例

  1. 创建路由路径上下文:
import { createContext, useContext, useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';

const CurrentRouteContext = createContext();

// 上下文提供者组件
export function CurrentRouteProvider({ children }) {
  const location = useLocation();
  const [currentPath, setCurrentPath] = useState(
    `${location.pathname}${location.search}`
  );

  // 路由变化时更新当前路径
  useEffect(() => {
    setCurrentPath(`${location.pathname}${location.search}`);
  }, [location]);

  return (
    <CurrentRouteContext.Provider value={currentPath}>
      {children}
    </CurrentRouteContext.Provider>
  );
}

// 自定义钩子,方便组件获取当前路由路径
export function useCurrentRoute() {
  return useContext(CurrentRouteContext);
}
  1. 在App根组件中挂载上下文提供者:
import { BrowserRouter } from 'react-router-dom';
import { CurrentRouteProvider } from './CurrentRouteContext';

function App() {
  return (
    <BrowserRouter>
      <CurrentRouteProvider>
        {/* 你的页面/组件 */}
      </CurrentRouteProvider>
    </BrowserRouter>
  );
}
  1. 创建带路由路径注入的Axios钩子:
import axios from 'axios';
import { useCurrentRoute } from './CurrentRouteContext';

export function useApi() {
  const currentRoute = useCurrentRoute();
  const api = axios.create({ baseURL: '/api' });

  api.interceptors.request.use(config => {
    config.headers['X-Source-Route'] = currentRoute;
    return config;
  });

  return api;
}
  1. 在组件中使用:
import { useApi } from './path/to/useApi';

function OrderList() {
  const api = useApi();

  const fetchOrders = async () => {
    const response = await api.get('/orders');
    // 处理响应
  };

  return <button onClick={fetchOrders}>获取订单列表</button>;
}

适用场景

当你需要传递的是React路由的精确路径(不含域名、端口等),或者应用存在路由重写、多路由实例等特殊场景时,这个方案能确保拿到的是当前React路由的真实路径。

注意事项

  • 自定义请求头的字段名需和后端提前约定,避免与标准HTTP头冲突。
  • 若涉及跨域请求,后端需在CORS配置中添加允许该自定义头(如Access-Control-Allow-Headers: X-Source-URL),否则浏览器会拦截请求。
  • 测试时覆盖路由切换、页面刷新、跨域请求等场景,确保请求头的准确性。

内容的提问来源于stack exchange,提问作者TruMan1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:39:54