【问题标题】:because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled因为它的 MIME 类型 ('text/html') 不可执行,并且启用了严格的 MIME 类型检查
【发布时间】:2018-08-20 12:05:02
【问题描述】:

我正在使用 nodejs 和 webpack4,我正在尝试将 main.js 文件链接到 index.html。我尝试了网络上所有可能的解决方案,但它们似乎都不适合我。我是新手,欢迎提出建议请让我知道我做错了什么。

这是我看到的错误日志:


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

public/index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title> 
</head>
<body>

    <form action="/" method="POST" accept-charset="utf-8">
        <input type="email" name="email" placeholder="Email">
        <input type="submit" name="submit">
    </form>

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

</body>
</html>

/app.js

const express = require('express');
const app  = express();
const http = require('http');

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

app.post('/', function( req ,res){
    res.send("Success");
});

app.listen(3000, function(){
    console.log('Server running on port 3000');
});

文件结构

news_letter //Root directory
|_ dist
|   |_ main.js
|_ public
|   |_ index.html
|_ src
|   |_ index.js
|_ app.js

【问题讨论】:

    标签: node.js


    【解决方案1】:

    您需要将main.js 文件放在公用文件夹中。

    看起来您将main.js 文件放在dist/ 文件夹中,将index.html 文件放在public/ 文件夹中。

    但您只将app.js 文件中的一个目录设置为“静态文件目录”

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

    html 中的每个路径都相对于公用文件夹中的路径。因此,将您的 dist/ 文件夹移动到 public/ 文件夹中,一切正常

    文件结构

    news_letter //Root directory
    |_ public
    |   |_ dist
    |   |   |_ main.js
    |   |_ index.html
    |_ src
    |   |_ index.js
    |_ app.js
    

    【讨论】:

      【解决方案2】:

      就我而言,我还必须将中间件行更改为:

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

      代替:

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

      基于documentation的原因是:

      但是,您提供给 express.static 函数的路径是相对于您启动节点进程的目录的。如果您从另一个目录运行 express 应用,使用您要服务的目录的绝对路径会更安全:

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

      【讨论】:

      • 这个解决方案帮助了我。我使用 bootstrap sutdio 作为我的前端设计器,使用 html2pug npm 包导入我的 html 文件并最终遇到与 OP 相同的问题。在我的 UI 中保留路径 assets/js 等,我将路径 /public 更改为 /assets 并在静态路径函数前面添加 /assets,如上所示。 app.use('/assets', express.static(path.join(__dirname, '/assets')));
      猜你喜欢
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 2018-09-30
      • 2018-09-20
      • 2017-10-02
      • 2017-10-07
      • 2018-04-17
      • 2015-07-25
      相关资源
      最近更新 更多