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

Next.js 15(App Router)服务端组件如何获取当前路由/请求URL?

在Next.js 15 App Router中获取page.tsx方法所属路由/请求URL(避开中间件Header方法)

根据Next.js 15 App Router的架构,不同类型的组件(Server/Client)和方法(普通函数/Server Action)有不同的实现方式,以下是无需依赖中间件Header的可行方案:

Server Components(默认类型)

Server Components运行在服务器端,可以直接调用Next.js提供的内置API获取请求上下文:

1. 用request()函数直接获取完整URL(Next.js 15+)

Next.js 15新增的request()函数返回标准的Request对象,直接访问url属性即可拿到完整请求地址:

import { request } from 'next/server';

export default async function Page() {
  const req = request();
  const fullUrl = req.url;
  const pathname = new URL(fullUrl).pathname;

  // 在自定义方法中使用
  async function processServerData() {
    console.log('当前请求完整URL:', fullUrl);
    console.log('当前路由路径:', pathname);
    // 业务逻辑...
  }

  await processServerData();
  return <div>Page Content</div>;
}

2. 用headers()函数提取路由信息

通过headers()获取Next.js内部传递的请求头,组合出URL:

import { headers } from 'next/headers';

export default async function Page() {
  const headersList = headers();
  const protocol = headersList.get('x-forwarded-proto') || 'http';
  const host = headersList.get('host');
  const pathname = headersList.get('x-nextjs-url');
  const fullUrl = `${protocol}://${host}${pathname}`;

  function logCurrentRoute() {
    console.log('当前路由路径:', pathname);
    console.log('完整请求URL:', fullUrl);
  }

  logCurrentRoute();
  return <div>Page Content</div>;
}

x-nextjs-url头包含当前路由的路径部分,结合host和协议即可生成完整URL。

Client Components(加'use client'指令)

Client Components运行在浏览器端,可借助Next.js的客户端路由钩子或浏览器原生API:

1. 用usePathname()获取路由路径

usePathname()是App Router专门用于获取当前路由路径的钩子:

'use client';

import { usePathname } from 'next/navigation';

export default function Page() {
  const pathname = usePathname();

  function handleClientAction() {
    console.log('当前路由路径:', pathname);
    // 用浏览器API获取完整URL
    const fullUrl = window.location.href;
    console.log('完整请求URL:', fullUrl);
  }

  return (
    <button onClick={handleClientAction}>查看当前路由信息</button>
  );
}

2. 浏览器原生API直接获取

如果不需要Next.js的路由钩子,直接用window.location相关属性也能拿到完整信息:

'use client';

export default function Page() {
  function logUrlInfo() {
    console.log('当前路由路径:', window.location.pathname);
    console.log('完整请求URL:', window.location.href);
    console.log('主机地址:', window.location.host);
  }

  return <div onClick={logUrlInfo}>点击查看URL信息</div>;
}

Server Actions(加'use server'指令)

Server Actions运行在服务器端,可通过两种方式获取路由信息:

1. 在Action内部调用headers()

直接在Server Action中使用headers()获取请求上下文:

import { headers } from 'next/headers';

export default function Page() {
  async function myServerAction() {
    'use server';
    const headersList = headers();
    const fullUrl = `${headersList.get('x-forwarded-proto') || 'http'}://${headersList.get('host')}${headersList.get('x-nextjs-url')}`;
    console.log('Server Action 所属请求URL:', fullUrl);
    // 业务逻辑...
  }

  return <button onClick={myServerAction}>执行Server Action</button>;
}

2. 从组件传递路由参数

先在组件中获取路径,再作为参数传给Server Action:

import { usePathname } from 'next/navigation';

export default function Page() {
  const pathname = usePathname();

  async function myServerAction(currentPath: string) {
    'use server';
    console.log('Server Action 所属路由路径:', currentPath);
    // 如需完整URL,可结合headers()获取host和协议
    const headersList = headers();
    const fullUrl = `${headersList.get('x-forwarded-proto') || 'http'}://${headersList.get('host')}${currentPath}`;
    console.log('完整URL:', fullUrl);
  }

  return <button onClick={() => myServerAction(pathname)}>执行Server Action</button>;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 01:35:13