在next.js服务器端页面组件(在app目录下),如何获取当前url?

问题描述 投票:0回答:3

我正在使用 next.js 版本 13。 实验应用程序目录,无权访问 getServerSideProps()

“app”目录中的页面默认是服务器端的。

在 page.js 中,我正在尝试获取当前页面的 url。

我该怎么做?

export default async function myPage(props) {
    const prot =  // HTTP or HTTPS
    const domain = //www.myserver.com
    const port = //3000
    ... and so on.
    
    
}


我看到了这个解决方案: 在nextjs中获取URL路径名

但是“接下来 外部'不适用于服务器组件。

编译时出现此错误: 您有一个导入 next/router 的服务器组件。请改用下一个/导航。

next.js server-side-rendering
3个回答
1
投票

页面的另一个选项是导入

next/headers
,然后执行以下操作:

const headersList = headers();
const host = headersList.get("host");
const urlPath = headersList.get("next-url");

0
投票

我不知道您的用例是什么,但我需要获取当前网址,以便我可以使用

redirectTo
参数将未经身份验证的用户重定向到登录页面。

根据 Next.js 文档

布局无法访问当前路线段

这可以使用中间件来实现:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export async function middleware(req: NextRequest) {

  if (req.nextUrl.pathname.startsWith('/protected/path') && userIsUnauthenticated()) {
    const currentUrl = req.nextUrl;
    const redirectTo =
      currentUrl.pathname + currentUrl.search + currentUrl.hash;

    const redirect = new URL('/login', req.url);
    redirect.searchParams.set('redirectTo', redirectTo);
    return NextResponse.redirect(redirect);
  }

  return NextResponse.next();
}

这里的关键是

NextRequest.nextUrl
哪个

使用额外的便捷方法(包括 Next.js 特定属性)扩展原生 URL API。

示例:

const protocol = req.nextUrl.protocol // HTTP or HTTPS
const domain = req.nextUrl.hostname // www.myserver.com
const port = req.nextUrl.port // 3000

0
投票

您可以使用 @nimpl/getters 为此

import { getPathname } from '@nimpl/getters/get-pathname'

export default function Component() {
    const pathname = getPathname()

    return (
        // ...
    )
}
© www.soinside.com 2019 - 2024. All rights reserved.