自从应用本地化中间件查询参数后,现在永远不会在 URL NextJs 13 中传递

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

我已经编写了本地化中间件并将其应用到我的 NextJS13 应用程序中,因此该网站有两种语言环境可供翻译。然而我发现现在查询参数不再通过在 Next Link 组件中传递的 url。

当我控制台记录请求时,我可以在中间件中看到搜索参数位于请求 URL 中。但是当重写时,我们一起丢失了搜索参数。

如何重写网址以保留其搜索参数?

中间件代码如下:

import { NextFetchEvent, NextMiddleware, NextRequest, NextResponse } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
import { request } from "http";
import { i18n } from "@/i18n.config";

let defaultLocale = "en-US";

function getLocale(request: NextRequest): string | undefined {
  const negotiatorHeaders: Record<string, string> = {};
  request.headers.forEach((value, key) => (negotiatorHeaders[key] = value));

  // @ts-ignore locales are readonly
  const locales: string[] = i18n.locales;
  const languages = new Negotiator({ headers: negotiatorHeaders }).languages();

  const locale = match(languages, locales, defaultLocale);

  return locale;
}

export default function localisationMiddleware(middleware: NextMiddleware) {
  return async (request: NextRequest, event: NextFetchEvent) => {
    // Check if there is any supported locale in the pathname
    const pathname = request.nextUrl.pathname;

    // console.log("Request url", request.url);
    const pathnameIsMissingLocale = i18n.locales.every(
      locale => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
    );

    // Redirect if there is no locale
    if (pathnameIsMissingLocale) {
      console.log("NO LOCALE REDIRECRING");
      const locale = getLocale(request);

      console.log("REQUEST", request);


      // e.g. incoming request is /products
      // The new URL is now /en-US/products
      return NextResponse.redirect(
        new URL(`/${locale}${pathname.startsWith("/") ? "" : "/"}${pathname}`, request.url)
      );
    }

    return middleware(request, event);
  };
}
typescript next.js localization middleware next.js13
1个回答
0
投票

我也有同样的问题,解决方法如下:

首先,在中间件中捕获参数,如下所示:

  const {
    nextUrl: { search },
  } = req;
  const urlSearchParams = new URLSearchParams(search);
  const params = Object.fromEntries(urlSearchParams.entries());

  const urlParams = '?' + new URLSearchParams(params);

这样,只需在重定向中传递你的 urlParams 即可,如下所示:

 return NextResponse.redirect(
    new URL(`/${locale}${pathname.startsWith("/") ? "" : "/"}${pathname}${urlParams}`, request.url)
  );
© www.soinside.com 2019 - 2024. All rights reserved.