我需要从给定的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)

其他回答

正如已经提到的,有一个尚未完全支持的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的修复

以下是我使用的解决方案:

const result = `${ window.location.protocol }//${ window.location.host }`;

编辑:

要增加跨浏览器兼容性,请使用以下方法:

const result = `${ window.location.protocol }//${ window.location.hostname + (window.location.port ? ':' + window.location.port: '') }`;

出于某种原因,所有的答案都是多余的。这就是一切:

window.location.origin

更多细节可以在这里找到:https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties

var http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);
console.log(`${req.protocol}://${req.get('host')}/${req.originalUrl}`);

要求的事情。protocol -给出你使用的协议(例如HTTP) get(host) -给出带有端口号的主机名(例如localhost:8080)