![](/img/trans.png)
[英]Use the same route for url and for url with a trailing slash in sammy.js
[英]CSS and JS not loading with trailing slash in URL
我正在本地構建一個 Node.js 服務器,它將在localhost:8080
偵聽。 登陸頁面是一個名為index.html
的 html 文件。 如果我輸入localhost:8080/index.html
,那么 HTML 以及 CSS 文件 ( main.css
) 和 JavaScript ( main.js
) 位於與index.html
相同的文件夾中,就會正常加載。 但是,如果我用斜杠輸入相同的 URL,如localhost:8080/index.html/
,它只會加載 html,而不是 CSS 或 JS。 我嘗試進入 Chrome 中的 HTML 頁面源代碼並單擊其中的 css 文件,它似乎在尋找localhost:8080/index.html/main.css
文件(從瀏覽器的地址欄中看到),這顯然不存在。 似乎出於某種原因,它假設index.html
是一個目錄。 任何幫助都會很棒。
編輯:處理路由的服務器部分如下所示(我剛剛開始,我正在嘗試不使用 Express.js 進行路由):
const http = require("http");
const fs = require("fs");
const path = require("path");
const url = require("url");
http.createServer(function(request, response) {
function writeContentType(headerText) {
response.setHeader("Content-Type", headerText);
}
let requestedPath = url.parse(request.url, true).pathname;
requestedPath = requestedPath.replace(/^\/+|\/+$/g, "");
requestedPath = requestedPath.replace(/\//g, "\\");
requestedPath = "\\" + requestedPath;
if (requestedPath === "\\") requestedPath = "\\index.html";
if (!fs.existsSync(__dirname + requestedPath)) {
console.log("file does not exist, requested path is " + __dirname + requestedPath);
writeContentType("text/html");
response.write("<h1>Error 404</h1><h2>Page not found</h2>");
response.end();
} else {
let responseFile = fs.readFileSync(__dirname + requestedPath, function(err) {
console.log(err);
});
if (responseFile) {
let fileExtension = path.extname(requestedPath);
switch(fileExtension) {
case ".html" : writeContentType("text/html"); break;
case ".css" : writeContentType("text/css"); break;
case ".js" : writeContentType("text/javascript"); break;
case ".svg" : writeContentType("image/svg+xml"); break;
case ".jpg" :
case ".jpeg" : writeContentType("image/jpeg"); break;
}
response.end(responseFile);
}
}
}).listen(8080);
當時的想法是在剝離的開始和結束所有斜線requestedPath
,用反斜杠更換里面的任何斜杠,因為我的文件系統是Windows,然后在開頭添加一個反斜杠,然后查找文件系統中的文件。 我可能會在這里違背很多最佳實踐,我才剛剛開始。
無論您在哪里引用 JS 和 CSS 文件,請在前面使用“/”,以便它始終在根目錄中搜索文件。 例如,
href="/styles.css"
始終使用 express.static 來提供靜態文件
這是預期的行為,當您點擊localhost:8080/
您希望得到 index.html
因此,當您添加尾部斜杠時,它假定它是一個目錄並在那里查找您的文件。
嘗試使用 npm 包express-slash或制作自定義中間件,例如:
app.use(function(req, res, next) {
if (req.path.substr(-1) == '/' && req.path.length > 1) {
const query = req.url.slice(req.path.length);
res.redirect(301, req.path.slice(0, -1) + query);
} else {
next();
}
});
可以在這里找到類似的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.