由于不允许的 MIME 类型(“text/html”)而被阻止:Angular 8 部署在 tomcat 9.0.30 上无法提供资产

Blocked because of a disallowed MIME type (“text/html”) : Angular 8 deployed on tomcat 9.0.30 fails to serve the assets

我有一个项目,其中的用户界面基于angular 8,后端是一个springboot java 服务。整个项目是一个多模块项目,angular 部分是一个单独的模块,front-end builder 用于将 ui 代码打包到单个可执行 jar 中。使用嵌入式 tomcat 时,应用程序运行良好。我有一个新的 requirement 尝试在外部 tomcat 上单独部署 angular ui 部分。但是当我将 dist 文件夹复制到 webapps 文件夹并尝试为其提供服务时,浏览器阻止请求说:

Loading module from “http://localhost:8080/polyfills-es2015.js” was blocked because of a disallowed MIME type (“text/html”).

在做了一些 google 搜索后,我开始明白问题的发生是因为 angular 8 cli 无法将 type 属性添加到 script 标签 index.html。当我手动添加类型时,一切正常。任何人都可以帮助我理解为什么会发生这种情况,以及除了手动编辑之外的可能解决问题的方法。

生成 index.html :

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>My Application</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <i class="fas fa-chart-area"></i>
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body style="margin: 0;">
  <app-root></app-root>
<script src="runtime-es2015.js" type="module"></script><script src="runtime-es5.js" nomodule defer></script><script src="polyfills-es5.js" nomodule defer></script><script src="polyfills-es2015.js" type="module"></script><script src="styles-es2015.js" type="module"></script><script src="styles-es5.js" nomodule defer></script><script src="scripts.js" defer></script><script src="vendor-es2015.js" type="module"></script><script src="vendor-es5.js" nomodule defer></script><script src="main-es2015.js" type="module"></script><script src="main-es5.js" nomodule defer></script></body>

</html>

因此,总结一切有效的方法如下:

相关link

 <base href="/">

是问题所在,将其更改为您的上下文根目录。或者改成

<base href=".">

浏览器无法找到您的 JS 文件,因为它会查找与基本 href 相关的 JS 文件。

你的基础 href= "/" ,所以它会寻找 "localhost:8080/" 中的所有 js 文件, 但您的 JS 文件可能存在于 "localhost:8080/someRoot"

您可以想到的另一种解决方案是,在没有上下文根的情况下部署在 tomcat 的 ROOT 文件夹中,如果您的项目允许的话

服务器认为你的JS文件是HTML文件。

这可能是因为服务器端识别有问题或者JS文件不存在(服务器端没有发送404状态码?)或者里面没有js。

因此,它发送 Content-Type text/html

浏览器看到内容类型,认为这不是css并且不允许。

如果您指定类型(客户端)或更改类型服务器端,它应该可以工作。

这个问题困扰了我一段时间。对于那些像我一样不小心的人,请确保导入文件名末尾有 .js