我需要从给定的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
当前回答
console.log(`${req.protocol}://${req.get('host')}/${req.originalUrl}`);
要求的事情。protocol -给出你使用的协议(例如HTTP) get(host) -给出带有端口号的主机名(例如localhost:8080)
其他回答
适用于所有浏览器的简单答案:
let origin;
if (!window.location.origin) {
origin = window.location.protocol + "//" + window.location.hostname +
(window.location.port ? ':' + window.location.port: '');
}
origin = window.location.origin;
const full = location.protocol + '//' + location.host;
为什么不使用:
let full = window.location.origin
Window.location.protocol + '//' + window.location.host
以下是我使用的解决方案:
const result = `${ window.location.protocol }//${ window.location.host }`;
编辑:
要增加跨浏览器兼容性,请使用以下方法:
const result = `${ window.location.protocol }//${ window.location.hostname + (window.location.port ? ':' + window.location.port: '') }`;