如何获取带有子目录的根url



当我的应用程序托管在多个子目录中时,我想获得它的完整根路由url。每当我检索url时,我只会得到主机名和端口,或者当我尝试类似window.location.href的操作时,我会在url中得到我不想要的queryparams和路由。

例如:如果我的应用程序托管在:http://hostname/subdir1/subdir2/myapp我想得到http://hostname/subdir1/subdir2/无论当前路由器状态如何

您可以使用pop((和URL API来实现这一点:

const url = new URL(window.location.href);
let path = url.pathname.split("/");
path.pop();
url.pathname = path.join("/")
console.log(url.href)

最新更新