當我在瀏覽器 URL 中定義路由引數時,與該 URL 連接的路由會向我發送公用檔案夾(包含我的 CSS、JS 等)路由的錯誤。
應用程式的結構是這樣的:
app
|
|-- public
| └-- css
| └-- profile.css
|
|-- views
| └-- profile.html
|
|-- server.js
在我的 server.js 中,我有這個:
// server.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.set('views', path.join(__dirname, './views'))
app.get('/profile/:userId', (req, res) => {
res.sendFile(path.join(__dirname, './views/profile.html'))
})
app.listen(PORT, () => {
console.log(`Listening at port: ${PORT}`)
})
在我profile.html的身上,我已經像這樣鏈接了 CSS 檔案:
<link rel="stylesheet" href="./css/profile.css">
當我轉到 URL 時http://localhost:3000/profile/someId,HTML 可以正常運行,但是我的靜態檔案夾有一些錯誤,如下所示:
Refused to apply style from 'http://localhost:3000/profile/css/profile.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
當我:userId從檔案中洗掉引數時server.js,CSS 運行完美,如下所示:
app.get('/profile', (req, res) => {
res.sendFile(path.join(__dirname, './views/profile.html'))
})
uj5u.com熱心網友回復:
問題是您使用的是相對于當前目錄的路徑,./css/profile.css而不是相對于站點根目錄的路徑。
TL;DR:只需更改<link rel="stylesheet" href="./css/profile.css">為
<link rel="stylesheet" href="/css/profile.css">
現在這里有一個更完整的答案:
./css/profile.css意思是“從當前目錄開始,進入css檔案夾,獲取檔案profile.css”。當前目錄為http://localhost:3000/profile/someIdis http://localhost:3000/profile,所以瀏覽器會嘗試獲取http://localhost:3000/profile/css/profile.css. 通常,這只會給您一個“404 Not Found”錯誤,因為 CSS 檔案不存在(實際上位于http://localhost:3000/css/profile.css)。
但是,您的代碼使用引數:userId,因此當瀏覽器向服務器請求 時http://localhost:3000/profile/css/profile.css,服務器認為:userId是css/profile.css并且呼叫 GET 處理程式/profile/:userId。您的 GET 處理程式發回一些 HTML,但瀏覽器需要 CSS,因此瀏覽器說檔案型別(MIME 型別)錯誤。
至此,答案應該很清楚了:你需要做的就是找到正確的路徑。/css/profile.css意思是“去這個站點的根目錄(http://localhost:3000),去css檔案夾,然后得到檔案profile.css”。這就是你真正想做的事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/521275.html
