我收到“拒绝执行来自‘http://localhost:3000/js/dashboard/dashboard.js’的脚本,因为其 MIME 类型(‘text/plain’)不可执行

问题描述 投票:0回答:1

我的代码在我使用时有效

<script> //my js code </script> 

但是我试图将 JavaScript 代码放在 ejs(HTML) 文件之外,

  • 我创建了新的js文件,并将代码放入其中

  • 我导入到我的 ejs 文件中

    <script src="../js/dashboard/dashboard.js"></script>
    

我的浏览器向我显示此错误:

GET http://localhost:3000/js/dashboard/dashboard.js net::ERR_ABORTED 404 (Not Found)

dashboard:1 Refused to execute script from 'http://localhost:3000/js/dashboard/dashboard.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

当我进入邮递员并执行 http GET 请求以查看标头(内容类型)时:我注意到这一点:

如何更改 MIME 内容类型或只是避免此 MIME 错误。

这是我的建筑:

尝试避免 MIME 错误

html express browser ejs
1个回答
0
投票

我将冒险猜测您正在从

/public
目录中提供您的应用程序。你的
app.js
中的某些内容类似于:

app.use(express.static(__dirname + '/public'));`

app.use('/static', express.static(path.join(__dirname, 'public')));

如果是这样,这意味着您希望 front-end 使用的任何 JavaScript(例如 DOM 操作和添加事件侦听器等)都需要位于同一个

/public
目录中。从文件布局来看,
dashboard.js
位于它自己的
/js
目录中。这意味着它仅适用于后端上的 Node.js。

作为一个简单的解决方案,只需创建一个新文件夹:

/public/js
并将
dashboard.js
放入其中。

为了清楚起见,请将您的文件移至此处:

/public/js/dashboard.js

MIME type ('text/html')
是一个转移注意力的话题,因为如果您实际查看响应,可能会发现一些错误消息......以 HTML 形式呈现。

© www.soinside.com 2019 - 2024. All rights reserved.