简体   繁体   English

从React JS访问URL主机名

[英]Accessing the URL hostname from React JS

I'm trying to access the URL subdomain. 我正在尝试访问URL子域。 Traditionally in JavaScript I'd do 传统上使用JavaScript我会做

var full = window.location.host;
var parts = full.split('.');
var subdomain = parts[0];
// ...

However I'm calling this from a React JS component, and I get the following error - 但是我从React JS组件调用它,我得到以下错误 -

Encountered error "TypeError: undefined is not an object (evaluating 'window.location.host')"

It seems as though window.location.host doesn't work from React? 似乎window.location.host无法在React中运行? Does it not have access to the window? 它无法访问窗口吗?

I get there might be philosophical reasons to not do this, but I'd still be curious how to implement it if it's possible from React. 我认为可能有哲学上的理由不这样做,但我仍然很好奇如何实现它,如果它可以从React。

Thanks! 谢谢!

This is isomorphic so if it is being processed server side so you cannot access the window.location.href 这是同构的,所以如果它正在处理服务器端,那么你就无法访问window.location.href

For server side, you will need to look at the underlying request object to get the hostname: 对于服务器端,您需要查看底层请求对象以获取主机名:

http://expressjs.com/en/api.html#req.hostname http://expressjs.com/en/api.html#req.hostname

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

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