如何解决Spa 应用程序如何在运行时从动态配置文件设置基本 URL
front: react js 16.13.1,back: .net core 3.1,build: webpack 4.43.0
我必须在 base url
上为前后设置 run time
(子文件夹),此值在构建时不存在
在部署过程中为 dynamic
生成了一个 subdirectory
值,我们必须在后面和前面使用它。
For back 在 appsettings.json
上添加并在运行时读取。
对于客户端,我遇到了一些麻烦,我必须在很多地方添加从 servicePrefixUrl
中提取的 front-config.json
值:
- 在 index.html 中:
<base href="$$servicePrefixUrl$$" />
- 在路由器的基本名称中:
export const history = createBrowserHistory({
basename: $$servicePrefixUrl$$,});
<Router history={history}>
<App />
</Router>
);
- 在许多其他组件中。
front-config.json
例如:
{
"servicePrefixUrl": "/testSubfolder/"
}
或
{
"servicePrefixUrl": "/"
}
我尝试过的:
如果我们直接转到 url 到起始页,例如 https://example.com/testSubfolder/
为了获取 json 文件,我提出了一个 fetch 请求,为此我在 index.html 中添加了一个脚本:
<script>
(function () {
fetch("./front-config.json")
.then((response) => {
if (!response.ok) {
console.error("HTTP error " + response.status);
}
return response.json();
})
.then((json) => {
//set global variable
ServicePrefixUrl = json.servicePrefixUrl;
//add base tag with parsed values `"/testSubfolder/"`
document.head.innerHTML = document.head.innerHTML + "<base href='" + ServicePrefixUrl + "' />";
})
.catch(function (e) {
console.error("fetch front-config.json throw e",e);
});
})();
</script>
全局 ServicePrefixUrl 我可以在 createBrowserHistory 中用于 basename
export const history = createBrowserHistory({
basename: ServicePrefixUrl,});
当我导航到其他路径时,看起来一切正常,全局变量 ServicePrefixUrl
我可以在我需要的所有地方使用
但是如果我们在另一个路径中,例如 https://example.com/testSubfolder/users
fetch url 将是不正确的 https://example.com/testSubfolder/users/front-config.json
并且在这种情况下我找不到要解析的 json 因为我们不知道第一个子文件夹 "/testSubfolder /" 是基本名称或只是一条路线
任何想法如何为任何路径获取此配置文件?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com(将#修改为@)