簡體   English   中英

Node.js、Express 和 Mongoose 提供多個靜態文件

[英]Node.js, Express and Mongoose serving several static files

使用 Node.js、Express 和 Mongoose,我使用以下代碼在多個子目錄中同步提供多個靜態文件(工作正常):

fs.readdirSync(__dirname + "/../../../np-site/themes/default/client/")
    .forEach(function (dir) {
        app.use(express.static(__dirname +
            "/../../../np-site/themes/default/client/" + dir)
        );
    });

但是,部分 url 必須是動態的,具體取決於數據庫條目值:

express.static(__dirname + "/../../../np-site/themes/" + theme + "/client/" + dir)

我嘗試了幾種不同的方法,都無濟於事。 以下是我的第一次嘗試,當時對我來說最有意義(App模型是一個只能更新和檢索的對象):

App.find(function (err, appSettings) {
    fs.readdirSync(__dirname + "/../../../np-site/themes/" + appSettings[0].theme +
        "/client/").forEach(function (dir) {
            app.use(express.static(__dirname + "/../../../np-site/themes/" +
            appSettings[0].theme + "/client/" + dir)
        );
    });
});

然而,這不起作用,因此不會提供靜態文件。

我需要訪問的對象可用(通過 console.log 發現),但有些地方不對。

瀏覽器控制台確實會返回一條罕見的錯誤消息,指出文件的 MIME 類型 (CSS) 不正確,但我相信這是因為應用程序找不到正確的目錄(完全刪除該方法具有相同的結果)。

我認為它與 Mongoose 方法中的 app.use 有關,但我不確定。

有人可以對這個沮喪的靈魂有所了解嗎? 我感覺好像我走錯了路。

問題是您正在異步添加中間件(因為App.find()最有可能執行異步操作),這會導致您的動態中間件被添加(可能)所有靜態定義的中間件和路由處理程序之后。

Express 按照添加的順序執行中間件和路由處理程序。

該解決方案將延遲添加任何其它的中間件或路由處理,直到你的fs.readdirSync()但你的內部App.find()回調)。 一種簡單的方法是簡單地將其他中間件和路由處理程序添加到您在fs.readdirSync()之后調用的函數中:

var baseThemePath = __dirname + "/../../../np-site/themes/";
App.find(function (err, appSettings) {
  var themePath = baseThemePath + appSettings[0].theme + "/client/";
  fs.readdirSync(themePath).forEach(function(dir) {
    app.use(express.static(themePath + dir));
  });
  setupStatic();
});

function setupStatic() {
  app.use(express.static('public'));
  app.get('/', function(req, res) {
    res.send('Hello world');
  });
  // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM