【问题标题】:Express routing static file: Failed to load module script快速路由静态文件:加载模块脚本失败
【发布时间】:2020-07-08 09:17:10
【问题描述】:

我以与往常一样的方式为我的 Angular 9 应用程序提供服务,这是我第一次遇到这个问题。

我不断收到以下错误:“加载模块脚本失败:服务器以“text/html”的非 JavaScript MIME 类型响应。

我已经在网上搜索了答案,但似乎找不到任何可以解决问题的方法。我所做的一切似乎都遵循给出的建议。我想知道这是否是 Angular v9 的新问题?

我的 express app.js 位于我的 Angular 项目的另一个文件夹中。以下是我的文件夹结构:

  • 客户

    • 分布
      • index.html
  • 中层

    • app.js

app.js:

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

app.get('*/', (req, res) => { 
    const indexFile = path.join(__dirname, '../client/dist/index.html');
    res.sendFile(indexFile);
})

文件路径是正确的,我已经通过控制台记录了它,所有这些都加起来了。我将 angular.json 中的输出路径也更改为 dist 而不是另一个子文件夹。

我仍然收到此错误。有人可以帮忙吗?

【问题讨论】:

  • 你没有提到你得到了什么错误。
  • 你试过res.sendFile('../client/dist/index.html', {root: __dirname })吗?
  • @MorKadosh 哦,我很傻,谢谢你更新了我的问题。
  • 你试过类似app.use(express.static(path.join(__dirname, '../client/dist')))的东西吗? More here
  • @DhruvShah 我在尝试使用它时收到“ForbiddenError: Forbidden”。

标签: node.js express angular9 production dirname


【解决方案1】:

您必须为此使用express.static():

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

这里的问题是你总是用index.html文件响应,如果文件包含一些<script>标签,那么浏览器会期望收到.js文件但是你的服务器用.html文件响应,那就是为什么会出现错误。

【讨论】:

    【解决方案2】:

    非常感谢 sebastian-kaczmarek 提供此解决方案。

    有效答案如下:

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

    感谢您的支持。

    【讨论】:

      猜你喜欢
      • 2019-10-31
      • 2017-08-16
      • 2017-11-04
      • 2021-12-10
      • 2018-12-28
      • 2022-10-16
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多