繁体   English   中英

React 和 React Router 中的子域路由

[英]Subdomain Routing in React and React Router

我有 3 种类型的用户,我们希望为项目维护相同的代码库,而不是拥有 3-4 个代码库,因为大多数视图只是对用户类型的主观。

管理员 > admin.example.com

版主 > 版主.example.com

品牌 > 品牌.example.com

我的 React App 结构

src
-BaseRoutes.js <--- Should handle by subdomain logic
- modules
-- admin
---- AdminRoutes.js <---- handles all Admin route logic
---- components
---- pages
-- moderator
---- ModeratorRoutes.js <---- handles all Moderator route logic
---- components
---- pages
-- brands
---- BrandsRoutes.js <---- handles all Brands route logic
---- components
---- pages
- components
- pages

每种类型的用户都有自己的身份验证以允许访问内部路由。 我找到了一个 function 来拆分域并使用以下方法进行路由:

let host = window.location.host;
let protocol = window.location.protocol;
let parts = host.split(".");
let subdomain = "";
// If we get more than 3 parts, then we have a subdomain
// INFO: This could be 4, if you have a co.uk TLD or something like that.
if (parts.length >= 3) {
  subdomain = parts[0];
  // Remove the subdomain from the parts list
  parts.splice(0, 1);
  // Set the location to the new url
  window.location = protocol + "//" + parts.join(".") + "/" + subdomain;
}

这是在 React 中处理基于子域的路由的正确方法吗? 我从来没有为多种用户类型使用过一个代码库。 对正确的实施感到困惑。

您应该检查当前 url 的子域并将其与特定用户角色匹配,然后在反应路由器中您可以使用该简单逻辑,以便仅呈现特定于角色的路由:

<Router history={history}>
          {isAdmin &&
            <Route component={AdminViews} />
          }
          {isModerator &&
            <Route component={ModeratorViews} />
          }
...
          <Route path="/tnc" exact={true} component={CommmonRouteForAllRoles} />
</Router>

例如 AdminViews 可能如下所示:

export const AdminViews = () => {
  return (
    <Switch>
          <Route path="/" exact={true} component={AdminHome} />
          <Route path="/other" exact={true} component={AdminOtherRoute} />
          <Route path="/sign-in" exact={true} component={AdminSignIn} />
    </Switch>
  );
};

我猜你的服务器应该能够实现这一点,例如,你可以为管理员和版主创建子域,而用户域将是基本路由,所以如果管理员要登录,他会去admin.yourapp.com ,版主去moderator.yourapp.com然后处理身份验证逻辑,如果您使用 react-router 则视图不会真正成为问题

暂无
暂无

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

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