我需要从给定的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)
其他回答
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
}
var getBasePath = function(url) {
var r = ('' + url).match(/^(https?:)?\/\/[^/]+/i);
return r ? r[0] : '';
};
实际上,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: '');
使用ES6模板文字:
Const url = ' ${location.protocol}//${location.hostname}${location.port?':'+location.port: "} '; . getelementbyid(“结果”)。innerText = url; < div id = "结果" > < / div >
你可以简化为:
Const url = ' ${location.protocol}//${location.host} '; . getelementbyid(“结果”)。innerText = url; < div id = "结果" > < / div >
正如已经提到的,有一个尚未完全支持的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的修复