我正在尝试将 url / 重定向到我的默认语言的 url,默认语言位于 i18n 文件中。
但是,我仍然在 / 页面上收到 404 错误,但如果我输入 /en 就可以了。中间件.js
我的页面位于 src/app/[lang]
我的应用程序根目录下没有页面
中间件.js
import { NextResponse } from 'next/server'
import { i18n } from './i18n.js'
import { match as matchLocale } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
function getLocale(request) {
console.log("getLocale");
// Negotiator expects plain object so we need to transform headers
const negotiatorHeaders = {}
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value))
// @ts-ignore locales are readonly
const locales = i18n.locales
// Use negotiator and intl-localematcher to get best locale
let languages = new Negotiator({ headers: negotiatorHeaders }).languages(
locales
)
const locale = matchLocale(languages, locales, i18n.defaultLocale)
return locale
}
console.log("middleware not function");
export function middleware(request) {
const pathname = request.nextUrl.pathname;
console.log("middleware");
// Check if the pathname is the root path
if (pathname === '/') {
const locale = getLocale(request)
// Redirect to the default locale
return NextResponse.redirect(
new URL(
`/${locale}`,
request.url
)
)
}
// Check if there is any supported locale in the pathname
const pathnameIsMissingLocale = i18n.locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
)
// Redirect if there is no locale
if (pathnameIsMissingLocale) {
const locale = getLocale(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
)
)
}
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
}
i18n.js
export const i18n = {
defaultLocale: 'en',
locales: ['en', 'nl'],
}
dictionaries.js
import 'server-only'
const dictionaries = {
en: () => import('../../../dictionaries/en.json').then((module) => module.default),
nl: () => import('../../../dictionaries/nl.json').then((module) => module.default),
}
export const getDictionary = async (locale) => dictionaries[locale]()
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverActions: true
},
}
module.exports = nextConfig
[语言]/layout.jsx
import "./globals.css";
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({ children, params }) {
return (
<html lang={params.lang}>
<body>{children}</body>
</html>
);
}
[语言]/page.jsx
"use server";
import { getDictionary } from "./dictionaries";
export default async function Page({ params: { lang } }) {
const dict = await getDictionary(lang); // en
return <button>{dict.products.cart}</button>; // Add to Cart
}
因为当用户访问主页-“/”页面时。但在应用程序路由器中具有 [lang] 文件夹。它需要 url 中的参数。因此,在这种情况下,您应该将用户重定向到您的区域设置之一。例如:“/” -> 重定向到“/en”,你可以看看我的建议,如下代码:
// app/page.tsx
import { redirect } from 'next/navigation';
const RootPage = () => {
redirect('/en');
};
export default RootPage;