将jQuery插件导入Angular 2+拒绝执行脚本,因为其MIME类型('text / html')不可执行 [英] Importing jQuery plugin into Angular 2+ Refused to execute script because its MIME type ('text/html') is not executable
问题描述
我需要在HTML文件中加载JavaScript(jQuery插件)。但它似乎没有奏效。这是在Angular-CLI服务器上运行的(ng服务)这是HTML。
I need to load a JavaScript (jQuery plugin) in an HTML file. But it doesn't seem to be working. This is running on Angular-CLI server (ng serve) Here's the 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类型检查是
启用。
Refused to execute script from 'http://localhost:8080/test.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
我发现这个问题,解决方案似乎正在纠正键入
属性,但这并没有为我修复它。我试过 text / javascript
和 application / javascript
。
I found this question, where the solution seems to be correcting the type
attribute, but that didn't fix it for me. I tried text/javascript
and application/javascript
.
我需要在这做什么?
编辑:网络控制台显示脚本的404错误。表示请求没有可用的响应数据。内容类型为 text / html; charset = utf-8
The network console shows a 404 error for the script. Says the request has no response data available. Content type says text/html; charset=utf-8
注意:我最初将此作为一个比我的实际代码更简单的例子,因为我认为它不与Angular CLI服务器有关。可能是这种情况,所以我将我的示例恢复为我的实际代码。
NOTE: I originally posted this as a more minimal example than my actual code, as I didn't think it had to do with Angular CLI server. That may be the case, so I restored my example to the actual code I have.
推荐答案
尝试将js脚本放入 src / assets
文件夹。然后它应该由开发服务器提供正确的mime类型
Try putting your js script in the src/assets
folder. Then it should be served with correct mime type by the development server
然后像下面引用它
<script src="/assets/scripts/test.js" type="text/javascript"></script>
您可以将文件添加到脚本中,而不是在index.html中包含jquery和您的脚本的属性angular-cli.json
(或 angular.json
如果使用角度6)
Rather than including jquery and your script in index.html, you could add the files to the "scripts" properties of angular-cli.json
(or angular.json
if using angular 6)
"scripts":
[
//include jQuery here, e.g. if installed with npm
"../node_modules/jquery/dist/jquery.min.js" ,
"assets/scripts/test.js"
]
注意:别忘了重启 ng服务
修改 .angular-cli.json
或 angular.json
files
Note: Don't forget to restart ng serve
after modifying the .angular-cli.json
or angular.json
files
这篇关于将jQuery插件导入Angular 2+拒绝执行脚本,因为其MIME类型('text / html')不可执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!