简体   繁体   English

React 中的子域路由

[英]Subdomain routing in React

I am trying to build multipurpose website to React using react-router v5 for routing.我正在尝试使用 react-router v5 构建多用途网站以进行路由。 For normal routing we have routes like对于普通路由,我们有类似的路由

localhost:3000/posts localhost:3000/gallery本地主机:3000/帖子本地主机:3000/画廊

But for some other case I want to have subdomain lets say blog.但对于其他一些情况,我想要子域让我们说博客。

blog.localhost:3000 // render blog component blog.localhost:3000 // 渲染博客组件

or或者

subdomain.localhost:3000 // render some component. subdomain.localhost:3000 // 渲染一些组件。

For now this also renders the same component as localhost:3000.现在,这也呈现与 localhost:3000 相同的组件。

So, is there any way I can do this in react?那么,有什么办法可以让我做出反应吗?

Current routes look like this.当前路线如下所示。

function App() {
  return (
    <React.Fragment>
      <React.Suspense fallback={<></>}>
        <Router history={history}>
          <Switch>
            <Redirect exact from="/" to="/home" />
            <Route exact path="/login" component={LoginPage} />
            <ProtectedRoute exact={true} path="/profile" component={ProfilePage} />
            <ProtectedRoute exact={true} path="/home" component={HomePage} />
            <ProtectedRoute exact={true} path="/gallery/:subdomain" component={Gallery} />
            <Route exact path="/gallery/post/:subdomain/:postid" component={SinglePostView} />
            <Route component={PageNotFound} />
          </Switch>
        </Router>
      </React.Suspense>
    </React.Fragment>
  );
}

That's not possible, React is not a web server, React is a single page application.这是不可能的,React 不是 web 服务器,React 是单页应用程序。 You must host another React application on that subdomain.您必须在该子域上托管另一个 React 应用程序。

The problem is that React is not a web server, what you could do is make 2 different applications in a monorepo and use shared components.问题是 React不是web 服务器,你可以做的是在一个 monorepo 中创建 2 个不同的应用程序并使用共享组件。

For doing that, checkout this great article: https://dev.to/ynwd/how-to-setup-react-shared-components-in-monorepo-with-tailwind-webpack-and-npm-workspace-570n为此,请查看这篇精彩的文章: https://dev.to/ynwd/how-to-setup-react-shared-components-in-monorepo-with-tailwind-webpack-and-npm-workspace-570n

Assuming both blog & subdomain are served through the same React application you can use the below code:假设博客和子域都通过同一个 React 应用程序提供服务,您可以使用以下代码:

if (window.location.host.split(".")[0] !== "domain.com") {
  setSubDomain(window.location.host.split(".")[0]);
}

The setSubDomain function sets the extracted subdomain to a variable. setSubDomain function 将提取的子域设置为变量。

If however, the two subdomains are served by two different React applications, ideally you should set up the redirect at the server level.但是,如果这两个子域由两个不同的 React 应用程序提供服务,那么理想情况下,您应该在服务器级别设置重定向。

All the best!一切顺利!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM