构建一个不会在public_html根目录中运行的 Angular 应用程序



我实现了一个传统的angular应用程序。问题是它不会在域的根目录中运行,而是在子文件夹中运行。当我生成应用程序时,index.html看起来像:

<!DOCTYPE html>
<html>
<head>
<base href="/" />
<title>Backend</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.fc351d6e19ae3ad0f023.css"></head>
<body>
<app>Loading...</app>
<script src="runtime-es2015.858f8dd898b75fe86926.js" type="module"></script><script src="polyfills-es2015.7784ace277a2ec6cc920.js" type="module"></script><script src="runtime-es5.741402d1d47331ce975c.js" nomodule></script><script src="polyfills-es5.ae350e3469dc8aba722c.js" nomodule></script><script src="scripts.73905d6ee8dce4ede414.js"></script><script src="main-es2015.e77f6ad52f12c15144d3.js" type="module"></script><script src="main-es5.a7f7a3ca564e8841fd71.js" nomodule></script></body>
</html>

问题是脚本和样式没有加载,因为它们是在根目录中搜索的。我尝试更改基本节点,但不起作用。因此,每次构建时,我都必须编辑带有这些文件的完整路径的index.html文件。类似:

<!DOCTYPE html>
<html>
<head>
<base href="https://demo.com/backend/" />
<title>Backend</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://demo.com/backend/styles.fc351d6e19ae3ad0f023.css"></head>
<body>
<app>Loading...</app>
<script src="https://demo.com/backend/runtime-es2015.858f8dd898b75fe86926.js" type="module"></script><script src="https://demo.com/backend/polyfills-es2015.7784ace277a2ec6cc920.js" type="module"></script><script src="https://demo.com/backend/runtime-es5.741402d1d47331ce975c.js" nomodule></script><script src="https://demo.com/backend/polyfills-es5.ae350e3469dc8aba722c.js" nomodule></script><script src="https://demo.com/backend/scripts.73905d6ee8dce4ede414.js"></script><script src="https://demo.com/backend/main-es2015.e77f6ad52f12c15144d3.js" type="module"></script><script src="https://demo.com/backend/main-es5.a7f7a3ca564e8841fd71.js" nomodule></script></body>
</html>

你知道如何自动或优雅地做出这样的改变吗?TIA-

您可以使用web服务器将请求的url重新映射到所需的任何物理文件夹/文件。首先,将你的angular应用程序放在一个没有网络服务器服务的文件夹中。然后,使用ASP.NET Core,您可以创建这样的控制器:

[Route("[controller]/{*catchall}")]
public IActionResult CatchAll(string catchall)
{
// convert url to physical file path
string file = Path.Combine(folderForAngularApp, catchall);
// retrive the physical file and return it using the correct type
string suffix = Path.GetExtension(file).ToLower();
switch (suffix)
{
case ".js": return PhysicalFile(file, "text/javascript");
case ".html": return PhysicalFile(file, "text/html");
case ".css": return PhysicalFile(file, "text/css");
default: return NotFound();
}
}
}

这样你也可以控制对SPA的访问,即只允许经过身份验证的用户下载

最新更新