【问题标题】:Next-JS middleware ( NextRequest.nextUrl.locale ) return empty string in deployedNext-JS 中间件 ( NextRequest.nextUrl.locale ) 在部署时返回空字符串
【发布时间】:2022-09-28 02:47:05
【问题描述】:

我在 next-js 中间件中有一个错误

在中间件函数中返回一个 NextRequest 婴儿车 在 nextjs 文档中说:

The NextRequest object is an extension of the native Request interface, with the     
following added methods and properties:

- cookies - A Map with cookies from the Request. See Using cookies in Middleware
- nextUrl: Includes an extended, parsed, URL object that gives you access to Next.js 
- specific properties such as pathname, basePath, trailingSlash and i18n. Includes the 
- following properties:
- basePath (string)
- buildId (string || undefined)
- defaultLocale (string || undefined)
- domainLocale
  - defaultLocale: (string)
  - domain: (string)
  - http: (boolean || undefined)
  - locales: (string[] || undefined)
- locale (string || undefined)

这意味着我可以从 NextRequest.nextUrl.locale 访问当前语言环境。 很好,这在 localhost 中工作,我已经获得了一个语言环境。

但是在netlify中部署项目并在控制台中打印NextRequest.nextUrl.locale之后

console.log({locale: NextRequest.nextUrl.locale});

被退回给我

{ locale: \"\" }

含义 NextRequest.nextUrl.locale = \"\" & 空字符串

为什么这个错误?

那是我的代码

const middleware = async (req) => {
  if (
    req.nextUrl.pathname.startsWith(\"/_next\") ||
    req.nextUrl.pathname.includes(\"/api/\") ||
    PUBLIC_FILE.test(req.nextUrl.pathname)
  ) {
    return;
  }
  
  
  console.log({locale: req.nextUrl.locale});

  return;
};

export { middleware };

    标签: javascript node.js next.js middleware i18next


    【解决方案1】:

    您是否记得将国际化路由添加到您的 next.config.js

    https://nextjs.org/docs/advanced-features/i18n-routing

    我的经验是只有在使用 i18n 时才会填充语言环境。

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-12
      • 2023-02-15
      • 1970-01-01
      相关资源
      最近更新 更多