Next.js:呈现基于请求主机定制的动态页面 [英] Next.js: Render dynamic pages customized based on requesting host

查看:99
本文介绍了Next.js:呈现基于请求主机定制的动态页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据请求页面的域呈现具有自定义内容/样式的动态next.js页面. 基本上在多个域下运行一个next.js应用.

I want to render dynamic next.js pages with custom content / style based on the domain which requests the page. Basically run one next.js app under multiple domains.

我知道我必须进行某种自定义路由,但是不确切知道如何以及如何将主机信息传递到请求的页面,因此它会从数据库中获取匹配的数据.

I know that I have to do some sort of custom routing, but don't know exactly how and how I can pass the host information to the requested page, so it fetches the matching data from a database.

推荐答案

您应该能够在pages/_app.jsx文件static getInitialProps(context)方法中进行验证,并使用context验证请求的来源,然后返回组件的标志.

You should be able to verify this in your pages/_app.jsx file static getInitialProps(context) method and use the context to verify where the request is coming from then return a flag to the component.

示例:

// pages/_app.js

import app from 'next/app';

export default class MyApp extends app {
  static getInitialProps({ Component, router, ctx }) {
    let pageProps = app.getInitialProps({ Component, router, ctx });

    if (ctx.req.headers.host.match(/localhost/)) {
      pageProps = {
        ...pageProps,
        renderFrom: 'mydomain',
      }
    }

    return { pageProps };
  }

  render() {
    const { Component, pageProps } = this.props;
    return (
      <section id="app">
        <Component {...pageProps} />
      </section>
    );
  }
}

请注意,我调用app.getInitialProps来模仿next/app组件的行为,如源代码

Note that I call app.getInitialProps to mimic the next/app component behaviour as in the source code here

在您的pages/index.js中,您可以访问props.renderFrom,在那里您可以显示数据.

In your pages/index.js you will have access to props.renderFrom and there you can display data.

// pages/index.js

import React from 'react'

const Home = props => (
  <div>
    Rendering content for domain: {props.renderFrom}
  </div>
)

export default Home

由于您要验证_app.js中请求的来源,因此此属性将在所有容器(页面)中可用,因此您可以为应用程序使用相同的路由,并仅以不同的方式呈现数据.

Since you're verifying where the request comes from in _app.js this property will be available in all your containers (pages) so you can have the same routing for your application and just render data differently.

提示:您还可以使用next-routes来管理应用程序的路由,它比下一个附带的要好,并且在这里有一个自定义服务器,您还可以在其中管理流量.

Tip: You could also use next-routes to manage the routing for the application, it's better than the out next comes with, and in here you have a custom server where you can manage your traffic as well.

希望这对您有所帮助,并为您指明正确的方向.

Hopefully this helps you and points you in the right direction.

这篇关于Next.js:呈现基于请求主机定制的动态页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆