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

Next.js:在getServerSideProps中通过context获取URL片段

解决getServerSideProps中无法获取URL Hash参数的问题

首先要明确:URL中#后面的Hash片段是客户端浏览器专属内容,浏览器发送HTTP请求时不会把这部分数据传递给服务器。而getServerSideProps是在服务器端运行的函数,天然无法直接获取Hash里的参数。

下面提供两种可行的解决思路:

思路一:客户端解析Hash后,通过API请求传递参数

既然服务端拿不到Hash,就先在客户端解析出参数,再主动调用服务端API把参数传过去,获取需要的数据。

示例代码:

  1. 页面组件中解析Hash并请求API:
import { useEffect, useState } from 'react';

export default function SomePage() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // 解析URL Hash中的参数
    const hashParams = new URLSearchParams(window.location.hash.slice(1));
    const desiredParam = hashParams.get('desiredParam');

    if (desiredParam) {
      // 调用自定义API路由,传递参数
      fetch(`/api/get-data?desiredParam=${desiredParam}`)
        .then(res => res.json())
        .then(result => setData(result));
    }
  }, []);

  return <div>{data ? <p>获取到的数据:{JSON.stringify(data)}</p> : <p>加载中...</p>}</div>;
}
  1. 对应的API路由(pages/api/get-data.js):
export default function handler(req, res) {
  const { desiredParam } = req.query;
  // 这里处理业务逻辑,比如根据参数获取数据
  res.status(200).json({ param: desiredParam, message: '成功获取参数' });
}

思路二:客户端将Hash转为查询参数后重定向(适合需要服务端预渲染的场景)

如果页面需要依赖该参数做服务端预渲染,可以在客户端检测到Hash参数后,把它转成URL查询参数(?开头),然后重定向到新URL。这样getServerSideProps就能通过context.query拿到参数了。

示例代码:

import { useRouter } from 'next/router';
import { useEffect } from 'react';

export default function SomePage({ data }) {
  const router = useRouter();

  useEffect(() => {
    // 检查是否存在Hash参数
    if (window.location.hash) {
      const hashParams = new URLSearchParams(window.location.hash.slice(1));
      const desiredParam = hashParams.get('desiredParam');
      if (desiredParam) {
        // 重定向到带查询参数的URL
        router.push(`/some-folder?desiredParam=${desiredParam}`);
      }
    }
  }, [router]);

  return <div>{data ? <p>服务端预渲染的数据:{JSON.stringify(data)}</p> : <p>加载中...</p>}</div>;
}

export async function getServerSideProps(context) {
  const { desiredParam } = context.query;
  // 这里用参数做服务端逻辑,比如获取数据
  const data = desiredParam ? { param: desiredParam } : null;
  return { props: { data } };
}

注意:这种方法会改变URL(从带Hash变成带查询参数),如果业务不允许URL变化,建议用第一种思路。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:08:31