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

如何在Next.js中不使用window.location.href或React Router获取当前URL

在Next.js中不使用window.location.href或React Router获取当前URL

服务端场景(App Router / Pages Router)

  • App Router(服务端组件):利用Next.js内置的headers()函数提取请求头信息,拼接出完整URL:
import { headers } from 'next/headers';
import parse from 'url-parse';

export default function ServerComponent() {
  const headersList = headers();
  const protocol = headersList.get('x-forwarded-proto') || 'http';
  const host = headersList.get('host');
  const pathname = headersList.get('next-url') || '';
  const fullUrl = `${protocol}://${host}${pathname}`;
  
  const parsedUrl = parse(fullUrl, {});
  console.log(parsedUrl.href);
  return <div>当前URL:{parsedUrl.href}</div>;
}
  • Pages Router(getServerSideProps / getInitialProps):通过上下文里的req对象获取请求相关信息:
import parse from 'url-parse';

export async function getServerSideProps(context) {
  const { req } = context;
  const protocol = req.headers['x-forwarded-proto'] || 'http';
  const host = req.headers.host;
  const fullUrl = `${protocol}://${host}${req.url}`;
  
  const parsedUrl = parse(fullUrl, {});
  console.log(parsedUrl.href);
  return { props: { currentUrl: parsedUrl.href } };
}

export default function Page({ currentUrl }) {
  return <div>当前URL:{currentUrl}</div>;
}

客户端场景(不依赖window)

在客户端组件中,可借助App Router提供的usePathname和useSearchParams获取路径与参数,再结合服务端传递的域名信息组合完整URL:

'use client';
import { usePathname, useSearchParams } from 'next/navigation';
import parse from 'url-parse';

export default function ClientComponent({ domain }) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const searchString = searchParams.toString() ? `?${searchParams.toString()}` : '';
  const fullUrl = `${domain}${pathname}${searchString}`;
  
  const parsedUrl = parse(fullUrl, {});
  console.log(parsedUrl.href);
  return <div>当前URL:{parsedUrl.href}</div>;
}

注:域名domain需从服务端组件传递,避免直接使用window对象。

修正你提供的示例代码

你给出的url-parse用法有误,正确方式是传入完整URL字符串而非"hostname":

const parse = require("url-parse");
const fullUrl = "https://example.com/path?query=123"; // 替换为实际获取到的URL
const parsedUrl = parse(fullUrl, {});

console.log(parsedUrl.href); // 输出完整URL

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 13:50:17