首页 文章

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

提问于
浏览
8

我需要在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>

我收到此错误:

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

我找到this question,其中解决方案似乎正在纠正 type 属性,但这并不能解决它 . 我试过 text/javascriptapplication/javascript .

我需要做什么?

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

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

2 回答

  • 13

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

    然后像下面一样引用它

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

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

    "scripts":
     [
          //include jQuery here, e.g. if installed with npm
          "../node_modules/jquery/dist/jquery.min.js" ,
          "assets/scripts/test.js"
     ]
    

    Note :修改 .angular-cli.jsonangular.json 文件后别忘了重启 ng serve

  • 5

    我遇到过类似的问题

    issue

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

    <base href="./"> // remove dot (.) and your app will execute scripts
    

相关问题