【问题标题】:Subdomain in react router反应路由器中的子域
【发布时间】:2016-02-26 17:38:46
【问题描述】:

我想设置 react 路由器以用于子域。我不确定子域代理的逻辑应该在哪里。

我想要:

roxy.coolestblog.com/profile 路由到coolestblog.com/roxy/profile mohammed.coolestblog.com/profile 路由到 coolestblog.com/mohammed/profile benben.coolestblog.com/profile 路由到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

我已经让它在没有子域的情况下工作。

我怎样才能做到这一点,以便它在客户端和服务器上都可以工作?

【问题讨论】:

  • 您找到解决方案了吗?看来我也有同样的需求……
  • 如果你找到了解决办法,请分享
  • 回答了类似的问题here,以防万一
  • 你找到解决这个@collinglass的方法了吗?

标签: reactjs subdomain react-router


【解决方案1】:

虽然浏览器历史 API 限制了我们的能力,但我们可以直接与 window.location 交互以完成此操作。

在设置路由器之前,您可以通过以下方式修改 URL:

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 应该是什么做出任何假设,但解决这个问题很简单。

【讨论】:

  • 与从 cookie 中获取相比有优势吗?
猜你喜欢
  • 2019-01-07
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 2017-02-24
  • 2018-01-26
  • 1970-01-01
  • 2023-03-06
  • 2021-08-22
相关资源
最近更新 更多