javascript - 在 Next.js 页面中检索子域

标签 javascript reactjs typescript next.js react-typescript

我有一个 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 信息.

最佳答案

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] .
希望有帮助!

关于javascript - 在 Next.js 页面中检索子域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57469815/

相关文章:

javascript - React-hook-form 验证不适用于自定义字段数组

JavaScript : Simplifying array with reduce() and map() resulting in undefined

javascript - 如何创建一个具有 self 意识的原型(prototype)?

ios - 在 react-native 中如何检测右半边屏幕是否被点击?

reactjs - next.js 为 NextJs 设置 ESLint

css - Angular - 使用变换制作动画,但在动画完成时不应用绝对位置

angular - 表单值仅在第二步更改

javascript - 制作幻灯片旋转

javascript - d3.scaleSequential 不是一个函数

javascript - 如何停止 Node.js/Javascript 中的无限循环