我有一堆html文件,我想作爲靜態文件。但是,我需要的路線沒有任何.html在其中。使用express.js中的路由服務靜態文件
當路由是 example.com/about 它應該成爲about.html
的研究,我對服務的靜態文件做似乎表明,它不是完全可能的。那是對的,還是我錯過了什麼?
我有一堆html文件,我想作爲靜態文件。但是,我需要的路線沒有任何.html在其中。使用express.js中的路由服務靜態文件
當路由是 example.com/about 它應該成爲about.html
的研究,我對服務的靜態文件做似乎表明,它不是完全可能的。那是對的,還是我錯過了什麼?
試試這個。
app.use(express.static(path.join(__dirname, 'xyz')));
其中xyz是您試圖使靜態可用的文件夾。文件夾名稱相對於應用程序根目錄。
您需要使用路由器
app.get('/about', function(req, res) {
res.render('about.html');
});
,以滿足您的靜態文件,你應該設置爲HTML渲染引擎中間件
或者,如果你有很多的靜態文件,你可以使用之前中間件來爲你做它
您可以創建一個簡短的小片中間件使得w生病的過程,無論你配置它的預設名稱。任何不在該列表會去您的正常路線:
// create static file lookup table for the desired names
var staticFiles = ["about", "index", "home"].reduce(function(obj, item) {
obj["/" + item] = true;
return obj;
}, {});
app.use(function(req, res, next) {
// if the path is found in the lookup table, then
// add ".html" onto the end and get that file from the base directory
// of you could use any source directory for those files
if (staticFiles[req.path]) {
res.sendFile(path.join(__dirname, req.path + ".html"));
return;
}
next();
});
注:這非常仔細地僅提供特定的文件,所以沒有人可以去與其他類型的網址,在你的文件系統周圍窺探。
在此處,將文件從下面我們的基本目錄的子目錄中名爲「HTML」服務爲例:
app.use(function(req, res, next) {
if (staticFiles[req.path]) {
res.sendFile(path.join(__dirname, "html", req.path + ".html"));
return;
}
next();
});
在節點v0.12 +,你可以使用Set
對象你的靜態路由列表如下:
var staticFiles = new Set(["/about", "/index", "/home"]);
app.use(function(req, res, next) {
if (staticFiles.has(req.path)) {
res.sendFile(path.join(__dirname, "html", req.path + ".html"));
return;
}
next();
});
如果你有很多的靜態頁面,理想的方式是b e把它們放在一條路線上,我們稱之爲static.js
。它可以是這樣的,
module.exports = function() {
var router = require('express').Router();
var pages = {
'about-us': 'path/to/about-us',
'contact-us': 'path/to/contact-us'
};
router.get('/:page', function (req, res, next) {
if (! pages[req.params.page]) {
return next();
}
res.render(pages[req.params.page]);
});
return router;
};
連接這條路線到應用程序,app.use(require('./static')());
,你是好去。
這是行不通的,因爲它將路線指向約而不是about.html – Tim
時間是正確的。例如,您應該嘗試其他一些中間件。 https://github.com/divshot/clean-urls –