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

其他回答

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');

适用于所有浏览器的简单答案:

let origin;

if (!window.location.origin) {
  origin = window.location.protocol + "//" + window.location.hostname + 
     (window.location.port ? ':' + window.location.port: '');
}

origin = window.location.origin;

首先获取当前地址

var url = window.location.href

然后解析这个字符串

var arr = url.split("/");

你的网址是:

var result = arr[0] + "//" + arr[2]

ES6风格,具有可配置参数。

/**
 * Get the current URL from `window` context object.
 * Will return the fully qualified URL if neccessary:
 *   getCurrentBaseURL(true, false) // `http://localhost/` - `https://localhost:3000/`
 *   getCurrentBaseURL(true, true) // `http://www.example.com` - `https://www.example.com:8080`
 *   getCurrentBaseURL(false, true) // `www.example.com` - `localhost:3000`
 *
 * @param {boolean} [includeProtocol=true]
 * @param {boolean} [removeTrailingSlash=false]
 * @returns {string} The current base URL.
 */
export const getCurrentBaseURL = (includeProtocol = true, removeTrailingSlash = false) => {
  if (!window || !window.location || !window.location.hostname || !window.location.protocol) {
    console.error(
      `The getCurrentBaseURL function must be called from a context in which window object exists. Yet, window is ${window}`,
      [window, window.location, window.location.hostname, window.location.protocol],
    )
    throw new TypeError('Whole or part of window is not defined.')
  }

  const URL = `${includeProtocol ? `${window.location.protocol}//` : ''}${window.location.hostname}${
    window.location.port ? `:${window.location.port}` : ''
  }${removeTrailingSlash ? '' : '/'}`

  // console.log(`The URL is ${URL}`)

  return URL
}

host

var url = window.location.host;

返回localhost: 2679

主机名

var url = window.location.hostname;

返回本地主机