我需要从给定的URL中提取完整的协议、域和端口。例如:
https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer
>>>
https://localhost:8181
我需要从给定的URL中提取完整的协议、域和端口。例如:
https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer
>>>
https://localhost:8181
当前回答
const full = location.protocol + '//' + location.host;
其他回答
Window.location.origin就足以得到相同的。
protocol属性设置或返回当前URL的协议,包括冒号(:)。
这意味着如果你只想获得HTTP/HTTPS部分,你可以这样做:
var protocol = window.location.protocol.replace(/:/g,'')
对于域名,您可以使用:
var domain = window.location.hostname;
对于您可以使用的端口:
var port = window.location.port;
请记住,如果端口在URL中不可见,则端口将是空字符串。例如:
http://example.com/将为端口返回“” http://example.com:80/将返回80端口
如果在没有端口使用时需要显示80/443
var port = window.location.port || (protocol === 'https' ? '443' : '80');
console.log(`${req.protocol}://${req.get('host')}/${req.originalUrl}`);
要求的事情。protocol -给出你使用的协议(例如HTTP) get(host) -给出带有端口号的主机名(例如localhost:8080)
实际上,window.location.origin在遵循标准的浏览器中工作得很好,但你猜怎么着。IE没有遵循标准。
正因为如此,我在IE、FireFox和Chrome浏览器中使用了这个方法:
var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
但为了将来可能引起冲突的增强,我在“location”对象之前指定了“window”引用。
var full = window.location.protocol+'//'+window.location.hostname+(window.location.port ? ':'+window.location.port: '');
正如已经提到的,有一个尚未完全支持的window.location.origin,但不是使用它或创建一个新变量来使用,我更喜欢检查它,如果它没有设置为设置它。
例如;
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
实际上我在几个月前写过关于window.location.origin的修复