反应路由器中的子域 [英] Subdomain in react router
问题描述
我想设置反应路由器以用于子域.我不确定子域代理的逻辑应该在哪里.
I'd like to setup react router for use with subdomains. I'm unsure where the logic for subdomain proxying should lie.
我想要:
roxy.coolestblog.com/profile
路由到 coolestblog.com/roxy/profile
mohammed.coolestblog.com/profile
路由到 coolestblog.com/mohammed/profile
benben.coolestblog.com/profile
路由到 coolestblog.com/benben/profile
roxy.coolestblog.com/profile
to route to coolestblog.com/roxy/profile
mohammed.coolestblog.com/profile
to route to coolestblog.com/mohammed/profile
benben.coolestblog.com/profile
to route to coolestblog.com/benben/profile
另一个用例:
en.coolestblog.com/some-article
路由到 coolestblog.com/en/some-article
fr.coolestblog.com/un-article
路由到 coolestblog.com/fr/un-article
es.coolestblog.com/una-article
路由到 coolestblog.com/es/una-article
en.coolestblog.com/some-article
to route to coolestblog.com/en/some-article
fr.coolestblog.com/un-article
to route to coolestblog.com/fr/un-article
es.coolestblog.com/una-article
to route to coolestblog.com/es/una-article
我已经在没有子域的情况下工作了.
I already have it working without the subdomain.
我怎样才能做到这一点,让它在客户端和服务器上都能工作?
How can I achieve this so it works both on client and server?
推荐答案
虽然浏览器历史 API 限制了我们的能力,但我们可以直接与 window.location
交互来实现这一点.
While the browser history API limits our ability, we can interact directly with window.location
in order to accomplish this.
就在设置路由器之前,您可以通过执行以下操作来修改 URL:
Just before setting up your router, you can modify the URL by doing something like this:
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;
}
当然,这有其警告.例如,如果您不明确知道您的主机名,则无法正确确定是否存在子域.它不会对以下 URL 应该是什么做出任何假设,但解决这个问题很简单.
Of course, this has its caveats. For instance, if you do not know your host name explicitly, you cannot correctly determine if there is a subdomain or not. It does not make any assumptions about what the following URL should be, but it would be trivial to solve for that.
这篇关于反应路由器中的子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!