node.js - 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?目前是/
.
是的,我知道对此有很多问题,但没有有效的答案。
解决方案
您收到此消息是因为服务器没有使用 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 以查看服务器如何响应
推荐阅读
- python - 使用负索引调整大小的列表切片分配
- java - 为什么java不支持直接将操作数放入局部变量表的字节码?
- javascript - 重新加载页面时保留选定的选项值
- java - Android InApp 订阅架构
- go - Golang RestApi Mysql 插入查询
- django - 使用 Django 的电子商务网站导航栏
- javascript - 在 JavaScript Canvas 中,如何在使用函数移动画布后将其保留在画布中?
- c# - 如何为 DB2 表值函数传递日期参数
- python - 加权平均:自定义层权重在 TensorFlow 2.2.0 中没有变化
- sql - 如何将此更新删除和选择查询合并为一个?