由于应用了本地化中间件,查询参数现在不再通过url NextJs 13

p3rjfoxz  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(163)

我已经编写了本地化中间件并将其应用到我的NextJS 13应用程序中,因此该网站有两个本地化翻译。然而,我后来发现,现在查询参数不再通过正在通过一个下一个链接组件的网址。
当我在控制台记录请求时,我可以在我的中间件中看到搜索参数在请求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);
  };
}
vdgimpew

vdgimpew1#

我也有同样的问题,解决方法如下:
首先,在中间件中捕获参数,如下所示:

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)
  );

相关问题