8

我有一个pages/index.tsxNext.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:3000;langKey将是enfr)。如何从 Next.js 上下文中检索此信息?我尝试了 Router 对象,但它看起来不像在第一个/.

4

2 回答 2

7

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

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

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

希望有帮助!

于 2019-08-13T02:58:51.407 回答
1

我最近遇到了类似的问题,并找到了一个不同的简单解决方案:您可以使用重写将主机名作为路径变量放入路径中。这适用于服务器端和客户端,尽管我只在使用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.tsxpages/site/[siteHost]/index.tsx

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

于 2021-09-02T17:03:51.787 回答