首页 > 解决方案 > X-Content-Type-Options 在 Heroku 上使用 Node 阻止 CSS

问题描述

我正在尝试将 Node.js 应用程序部署到 Heroku。该应用程序的前端是用 Vue.js 编写的。Vue 构建输出/public位于 Node 应用程序中。它在从启动时完美运行,localhost并且可以作为https://localhost:8080/public.

当然,它不在 Heroku 上。标X-Content-Type-Options头由他们的服务器设置,阻止所有 CSS 和 JS 文件,我在 Chrome 中收到此错误消息:

Refused to apply style from 'https://my-awesome-app.herokuapp.com/css/app.5364ed87.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

我对我的静态文件进行了一些修改,发现出了什么问题。在生产版本index.html中包含如下链接:

<link href=/js/chunk-109f12d9.3bbd3c2d.js rel=prefetch>
<link href=/js/chunk-2d0bae5c.0ec2a734.js rel=prefetch>
<link href=/js/chunk-2d0f1192.aa2d5399.js rel=prefetch>
<link href=/js/chunk-f8fb7b5a.9218edff.js rel=prefetch>
<link href=/css/app.5364ed87.css rel=preload as=style>
<link href=/js/app.af503387.js rel=preload as=script>
<link href=/js/chunk-vendors.aa1329d3.js rel=preload as=script>
<link href=/css/app.5364ed87.css rel=stylesheet>

我发现如果我从href属性中删除开头的斜线,链接会突然开始工作。所以css/whatever.css行得通,/css/whatever.css不行。

我怀疑我在 Express 设置中启用静态目录的方式有问题。但我想不通是什么。你有什么主意吗?

const publicPath = path.join(__dirname, 'public');
this.express.use('/public', express.static(publicPath));

在任何地方添加斜线或删除它都没有帮助。我已经尝试了所有可能的组合。它不适用于/public, /public/, public/,public等。

是不是必须在Vue中设置基本URL?目前是/.

是的,我知道对此有很多问题,但没有有效的答案。

标签: node.jsexpressvue.jsheroku

解决方案


您收到此消息是因为服务器没有使用 css 响应,它很可能是html,更准确地说是浏览器实际识别为的 404 页面text/html

以下是可能的修复:

  • 检查您的 vue 应用程序是否实际上是使用所有 js 和 css 文件构建的(您可能错过了 vue 应用程序的构建步骤)

  • 用于heroku run bash在构建文件后检查文件

  • 使用 url 提供静态文件,/但也不要让其他路由无法到达,如下所示:

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

    确保静态设置是最后一项

  • 尝试直接在您的浏览器中访问 javascript 和 css url 以查看服务器如何响应


推荐阅读