[英]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.