express.static 和 CSS 文件的 MIME 类型错误 [英] MIME type error with express.static and CSS files

查看:51
本文介绍了express.static 和 CSS 文件的 MIME 类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 express 和 node.在我的 server.js 文件中,我有这段代码:

I'm using express and node. In my server.js file I have this piece of code:

app.use(express.static('/static'));

随后在我的静态目录中,我有一个 CSS 文件夹,然后是一个 style.css 文件.在我的 index.html 中,我像这样链接到工作表:

And subsequently in my static directory, I have a CSS folder, and then a style.css file. In my index.html, I link to the sheet like so:

  <link rel="stylesheet" type="text/css" href="/static/css/style.css">

但是,在我的本地主机中,我继续收到此错误:

However, in my local host I continue to get this error:

拒绝应用来自 'http://localhost:3500/static/css/style 的样式.css' 因为它的 MIME 类型 ('text/html') 不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查.

Refused to apply style from 'http://localhost:3500/static/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

我确信我的标签中的路径名是正确的,但我不明白为什么我会收到这个错误.我是否需要声明 CSS 文件被处理为 CSS 而不是 HTML?当我说 type="text/CSS" 时,我不是在这样做吗?如果没有,我需要在我的服务器文件中添加什么来解决这个问题?

I am sure that my path name in my tag is right, and I'm confused to why I'm getting this error. Do I need to declare that CSS files be processed as CSS and not HTML? Am I not doing that when I say type="text/CSS"? If not, what do I need to put into my server file to remedy this issue?

推荐答案

app.use(express.static('/static'));

意味着静态文件是从 /static 字面上提供的.在基于 Unix 的操作系统中,这是根目录 / 的直接子级.我不认为你这样做,但你不应该存储文件,更不用说该目录中可公开访问的文件了.相反,您可能正在寻找的是应用程序目录中的 static 目录.

means that the static files are served literally from /static. In a Unix-Based Operating System, this is a direct child to the directory root /. I don't think you do, but you shouldn't store files, let alone publicly accessible files in that directory. Instead what you are probably looking for is the static directory in your App's directory.

这是你如何告诉 express 使用它来服务器文件:

This is how you can tell express to use that one to server files:

app.use(express.static(__dirname + "/static"));

发生 MIME 类型错误是因为提供的文件可能是404 Not Found"Express 制作的页面,因为它找不到 CSS 文件.浏览器需要一个 CSS 文件,得到一个 HTML 文件并说 MIME 类型不适合.

The MIME Type Error is happening because the file served is likely a "404 Not Found" page made by Express, because it couldn't locate the CSS file. The browser expects a CSS file, gets an HTML file and says the MIME Type doesn't fit.

如果你不能在你的 HTML 中包含一个文件,总是双重检查,甚至更好的三重检查,该文件可以首先通过浏览器访问.

If you can't include a file in your HTML always double, or better even tripple check, that the file can be accessed through the browser first.

此外,文件然后位于 ... href=/...",而不是 ... href=/static/...";

Also, the files are then located in ... href="/...", not ... href="/static/..."

这篇关于express.static 和 CSS 文件的 MIME 类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆