在 express 中设置静态 javascript 文件的内容类型

setting content type for static javascript files in express

我正在使用 express 使用 es6 模块提供带有 js 文件的页面。 关于 es6 模块 - https://jakearchibald.com/2017/es-modules-in-browsers/

我的 server.js 文件是 -

const app = express();
app.use( express.static( __dirname + '/src' ));

app.get('*', (req, res) => {
   res.sendFile(path.join(__dirname + '/index.html'));
});
    
app.listen(8080, () => console.log('Listening on port 8080!'));

我的 index.html 是 -

<html lang="en">
  <body>
    <script type="module" src="./src/test.js"></script>
  </body>
</html>

在文件 test.js 中,我使用的是 es6 模块,因此脚本标记中的 type="module"

但是当我在浏览器中提供这个 html 时,test.js 脚本没有加载。它给出了错误 -

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

我尝试在 server.js 文件中使用它在 express 中为 js 文件添加 mime 类型 -

express.static.mime.define({'application/javascript': ['js']});

但还是一样的结果。我想我需要以某种方式从 express 发送 mime/content-type 以获得 js 文件,但是如何? 请帮忙。

它需要一个装载路径。 '/src' 在 -

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

不知道为什么。会更新的。

内容类型应由文件扩展名自动确定。

<script type="module" src="./src/test.js"></script>

如果您不想在 Express 应用程序中将静态目录挂载到 /src,您可能需要从脚本路径中删除 /src