无法加载 angular 生成的网页 (ng build --prod)

Can't load angular generated webpage (ng build --prod)

在使用“ng build --prod”部署我的 angular 应用程序后,我尝试打开 index.html 文件并检查我的 Web 应用程序。但它在 chrome、firefox 和 edge 网络浏览器中不显示任何内容。当我打开控制台并检查是否有任何错误后,它会显示 6 条错误信息。

我应该提到我的应用程序已成功编译并在 'http://localhost:4200/' 上运行。 在我尝试了另一个 angular 应用程序(新的)之后,但它在构建后出现了同样的错误。

错误:

1) 从来源 'null' 访问 'file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/runtime-es2015.edb2fcf2778e7bf1d426.js' 处的脚本已被 CORS 策略阻止:跨来源请求仅支持协议方案:http、数据、chrome、 chrome-扩展名,https。

2) 获取文件:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/runtime-es2015.edb2fcf2778e7bf1d426.js net::ERR_FAILED

3) 从来源 'null' 访问 'file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/polyfills-es2015.2987770fde9daa1d8a2e.js' 处的脚本已被 CORS 策略阻止:跨来源请求仅支持协议方案:http、数据、chrome、 chrome-扩展名,https。 index.html:36

4) 获取文件:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/polyfills-es2015.2987770fde9daa1d8a2e.js net::ERR_FAILED index.html:1

5) 从来源 'null' 访问 'file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/main-es2015.69da1b25d5a7a648b825.js' 处的脚本已被 CORS 策略阻止:跨来源请求仅支持协议方案:http、数据、chrome、 chrome-扩展名,https。 index.html:36

6) 获取文件:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/main-es2015.69da1b25d5a7a648b825.js net::ERR_FAILED

问题是您尝试 运行 应用程序时没有服务器为 Angular 生成的 js 包提供服务。 Angular 会异步加载js。

一个选项运行 live-server 编译目录

// Install live-server if you haven't
npm install -g live-server

// Run live-server on you dist
cd <project-compile-dist-path>
live-server

// Note: if you don't want to install live-server globally you
// can use npx
npx live-server <path-to-directory>

https://www.npmjs.com/package/live-server

您必须从 HTTP 服务器为项目的 dist/moduleapp01 文件夹提供服务。出于安全原因(您尝试执行的操作),浏览器会自动阻止从您的文件系统发出的某些请求。您可以使用 http-server (https://www.npmjs.com/package/http-server).

从您项目的根目录,您可以使用 http-server ./dist/moduleapp01 -p 4200 启动服务器并在浏览器中打开它 http://localhost:4200