将jQuery插件导入Angular 2+拒绝执行脚本,因为其MIME类型('text/html')不可执行

BBa*_*ger 8 html javascript jquery angular

我需要在HTML文件中加载JavaScript(jQuery插件).但它似乎没有奏效.这是在Angular-CLI服务器上运行的(ng服务)这是HTML.

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test</title>
  <base href="/">

  <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

  <script src="./test.js" type="text/javascript"></script>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

拒绝从' http:// localhost:8080/test.js ' 执行脚本,因为其MIME类型('text/html')不可执行,并且启用了严格的MIME类型检查.

我发现了这个问题,解决方案似乎正在纠正type属性,但这并不适合我.我试着text/javascriptapplication/javascript.

我需要做什么?

编辑:网络控制台显示脚本的404错误.表示请求没有可用的响应数据.内容类型说text/html; charset=utf-8

注意:我最初将此作为一个比我的实际代码更简单的示例发布,因为我认为它与Angular CLI服务器没有关系.可能是这种情况,所以我将我的示例恢复为我的实际代码.

Dav*_*vid 13

尝试将js脚本放在src/assets文件夹中.然后它应该由开发服务器提供正确的mime类型

然后像下面一样引用它

<script src="/assets/scripts/test.js" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)

您可以将文件添加到"脚本"属性angular-cli.json(或者angular.json如果使用角度6),而不是在index.html中包含jquery和您的脚本.

"scripts":
 [
      //include jQuery here, e.g. if installed with npm
      "../node_modules/jquery/dist/jquery.min.js" ,
      "assets/scripts/test.js"
 ]
Run Code Online (Sandbox Code Playgroud)

注意:ng serve修改.angular-cli.jsonangular.json文件后不要忘记重新启动


Was*_*siF 5

我遇到过类似的问题

问题

并通过简单的index.html文件更改解决

<base href="./"> // remove dot (.) and your app will execute scripts
Run Code Online (Sandbox Code Playgroud)