【问题标题】:Retrieving sub-domain in Next.js page在 Next.js 页面中检索子域
【发布时间】:2019-12-19 13:01:04
【问题描述】:

我有一个pages/index.tsx Next.js 页面,其代码如下所示:

import { ApolloProvider } from "@apollo/react-hooks"
import Client from "../db"

import Header from "../components/Header"

export default function Index() {
    return <ApolloProvider client={Client}>
        <Header langKey={langKey} />
    </ApolloProvider>
}

问题是,langKey 应该是访问页面的子域(例如,en.localhost:3000fr.localhost:3000langKey 将是 enfr)。如何从 Next.js 上下文中检索此信息?我尝试了 Router 对象,但它看起来不像在第一个 / 之前存储任何 URL 信息。

【问题讨论】:

    标签: javascript reactjs typescript next.js react-typescript


    【解决方案1】:

    getInitialProps 生命周期方法(doc's here)上,您可以访问服务器端的请求对象并解析主机头。

    Index.getInitialProps = async ({ req }) => {
      const subdomain = req.headers.host.split('.')[0];
      return { langkey: subdomain };
    };
    

    如果仅在客户端需要此信息,您可以在生命周期方法中的某处轻松解析 window.locationwindow.location.host.split('.')[0]

    希望有帮助!

    【讨论】:

      【解决方案2】:

      我最近遇到了类似的问题,并找到了一个不同的简单解决方案:您可以使用rewrites 将主机名作为路径变量放入路径中。这适用于服务器端和客户端,尽管我只在使用 getStaticPaths/getStaticProps 的页面上进行了测试;其他类型的页面渲染可能存在问题。

      只需将这样的内容添加到next.config.js

              rewrites: async () => {
                  // In order to support wildcard subdomains with different content, use a "rewrite" to include the host in the path
                  return [
                      {
                          source: '/:path*{/}?',
                          has: [
                              {
                                  type: 'host',
                                  value: '(?<siteHost>.*)',
                              },
                          ],
                          destination: '/site/:siteHost/:path*',
                      },
                  ];
              },
      

      注意 1:仅当初始请求与 /pages/ 中的文件不匹配时才使用此重写,因此要对其进行测试,您需要将现有内容移动到 site 子文件夹中,例如将pages/index.tsx 移动到pages/site/[siteHost]/index.tsx

      注意 2:由于 https://github.com/vercel/next.js/issues/14930,使用 source: '/:path*' 将不适用于主页 (/) - 这就是使用 source: '/:path*{/}?' 的原因

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-04
        • 1970-01-01
        • 2022-11-20
        • 1970-01-01
        • 2020-08-28
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多