getServerSideProps 访问当前浏览器url

doo*_*man 11 reactjs next.js

我正在调用 getServerSideProps 并传入 req 和 res 参数,如下所示:

export async function getServerSideProps({ req, res }) {}
Run Code Online (Sandbox Code Playgroud)

我需要获取当前浏览器的 url 路径,但在请求对象中找不到它。有没有办法在 getServerSideProps 中获取当前 url?

jul*_*ves 30

您可以使用resolvedUrl上下文参数中的字段。

export async function getServerSideProps({ req, res, resolvedUrl }) {
    console.log(resolvedUrl)

   // Remaining code
}
Run Code Online (Sandbox Code Playgroud)

getServerSideProps文档中:

resolvedUrl:请求 URL 的规范化版本,它去除了 _next/data客户端转换的前缀并包含原始查询值。

请注意,resolvedUrl不会返回 URL 的域部分,仅返回路径和查询字符串。