請注意,我閱讀了以下 StackOverflow 帖子,但沒有幫助: 由于 MIME 型別未加載樣式表
我可以使用 Express.js 創建一個靜態公共檔案夾,其中 index.html 可以識別 style.css 和 tool.js 檔案(分別位于 css 和 js 的公共子檔案夾中)。我在 index.html 檔案中使用了這一行:
<link rel="stylesheet" href="css/style.css">
<script src="js/tool.js" defer></script>
app.js 中的這一行:
app.use(express.static("public"))
好的:這行得通。現在,我不想使用靜態檔案夾,想一一處理請求。因此,我沒有定義一個快速靜態公用檔案夾,而是使用以下行:
app.get("/",(req,res) => {
res.sendFile('./public/index.html', {root: __dirname})
})
請注意,我在此階段從代碼中洗掉了 app.use(express.static("public"))。這適用于部署 index.html(位于公共檔案夾中),但 index.html 檔案無法識別CSS 樣式表。
我為 CSS 檔案路徑嘗試了以下替代方法:
<link rel="stylesheet" href="public/css/style.css">
<link rel="stylesheet" href="/public/css/style.css">
<link rel="stylesheet" href="./css/style.css">
同樣,我嘗試了 tool.js 的替代路徑,例如:
<link rel="stylesheet" href="/public/js/tool.js">
這沒有用。
這是錯誤訊息的示例:
Refused to apply style from 'https://www.example.com/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. www.example.com/:9 GET https://www.example.com/js/tool.js net::ERR_ABORTED 404 (Not Found) www.example.com/:1 Refused to execute script from 'https://www.example.com/js/tool.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
最終,我將 style.css 檔案和 tool.js 放在 index.html 檔案旁邊,鏈接路徑如下:
鏈接 rel="stylesheet" href="style.css">
這不起作用,并表明獲取 css 和 js 檔案的路徑不是主要問題,因為我收到了與上述相同的錯誤訊息。
如何在不使用app.use(express.static("public"))的情況下解決此問題。
uj5u.com熱心網友回復:
如何在不使用 app.use(express.static("public")) 的情況下解決此問題。
您可以為要服務的每個檔案撰寫顯式路由,就像您為/.
所以你需要:
app.get("/js/tool.js",(req,res) => {
res.sendFile('./public/js/tool.js', {root: __dirname})
})
… ETC。
請注意,靜態中間件不僅僅是提供檔案。它還處理諸如設定有助于快取的合理 HTTP 標頭之類的事情。我強烈建議使用它sendFile。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/515378.html
上一篇:html和css中的關系選擇器
