我想展示一個自定義的404頁面(包含html,css,img和ico)。當我替換第一個公共靜態主頁時,我知道我的404文件夾有效。但是,我相信我要麼不以正確的方式使用路線,要麼無法設置兩個靜態文件夾。對於Express.js 4.x,是否可以使用express.static兩次?
我不想使用模板視圖引擎。我希望在前端渲染一切。
我的項目如下所示:
404
--index.html
--error.css
--404.jpg
bin
--server.js
public
--index.html
routes
--index.js
package.json
app.js
app.js
...
var index = require(./routes/index); //works
...
app.use(favicon(__dirname + '/public/content/images/logo.ico'));
app.use(logger('dev'));
app.use(jsonParser);
app.use(urlencodedParser);
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'))); //love it
app.use('/', index); //this is fine
...
index.js
var express = require('express');
const path = require('path');
var router = express.Router();
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
router.use('/', express.static(path.join(__dirname, './404'))); // HALP!
module.exports = router;
我已經將目錄播放(欲以「 404'vs'./404')。我通過輸入「localhost:3000/error」來測試。所以如果我的路徑是'/ error',它應該仍然使用父路徑:'/'。該文件指出,只要我的路線放在最後,它應該仍然有效。我在沒有使用express.static的情況下測試了它,並使用了一個在控制檯上打印錯誤的匿名函數。
是不可能使用express.static()兩次?
是的,你可以使用多個'express.static()'。這只是中間件,你可以擁有儘可能多的中間件。他們將按照您註冊的順序進行搜索。目前還不清楚你想要完成什麼。對於靜態路由幫助,請顯示幾個示例,指出要在文件系統中加載特定文件的準確URL,並準確顯示文件在您的文件系統中的位置。 – jfriend00
不可能使用任何路徑嗎?我想在主頁以外的任何路徑'/'上使用'express.static()'。換句話說,爲什麼'router.use('/',express.static(path.join(__ dirname,'./404');'not working?')在我移除靜態測試console.log時起作用。 – DeadSupra
僅供參考,自定義404頁面不需要'express.static()'通常,您只需創建所需的404中間件處理程序作爲最後的中間件,然後創建'res.sendFile()'您想要的任何文件顯示404處理程序示例:https://expressjs.com/en/starter/faq.html。如果您只想將完成的HTML文件發送到客戶端(無服務器端呈現),請使用' res.sendFile(someLocalFilePath)'404中間件' – jfriend00