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

3
使用“ng build --prod”部署我的Angular应用程序后,我尝试打开index.html文件并检查我的Web应用程序。但是在Chrome、Firefox和Edge Web浏览器中都没有显示任何内容。然后我打开控制台并检查是否有任何错误,它会显示6个错误消息。

6 errors in my webapp

我应该提到,我的应用程序在 'http://localhost:4200/' 上成功编译并运行。之后,我尝试了另一个 Angular 应用程序(新的),但是在构建后出现了相同类型的错误。
错误:
1)访问 'file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/runtime-es2015.edb2fcf2778e7bf1d426.js' 的脚本被来自 'null' 的 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。
2)GET file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/runtime-es2015.edb2fcf2778e7bf1d426.js net::ERR_FAILED
3)访问 'file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/polyfills-es2015.2987770fde9daa1d8a2e.js' 的脚本被来自 'null' 的 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。
4) 获取 file:///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、data、chrome、chrome-extension、https。 index.html:36
6) 获取 file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/main-es2015.69da1b25d5a7a648b825.js 失败 net::ERR_FAILED

如果您正在使用VS Code,则可以使用Live Server,没有问题。 - nitishk72
了解更多关于 CORS 的内容,以便更好地理解该策略。 - nitishk72
你需要启动应用程序。这正是内置服务器在本地主机上的4200端口所做的。仅打开HTML文件是行不通的。 - Jeremy Thille
2个回答

8
问题是您正在尝试在没有服务器提供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


1
你需要从HTTP服务器上提供项目的dist/moduleapp01文件夹。由于安全原因(你尝试的操作),浏览器会自动阻止一些从文件系统发出的请求。你可以使用http-serverhttps://www.npmjs.com/package/http-server)。
从你的项目根目录开始,你可以使用http-server ./dist/moduleapp01 -p 4200启动服务器,并在浏览器中打开它:http://localhost:4200

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接