簡體   English   中英

Node.js Express - 訪問根域時不會調用app.all(“*”,func)

[英]Node.js Express - app.all(“*”, func) doesn't get called when visiting root domain

我正在嘗試設置一個在每個頁面加載時調用的全局函數,無論它在我的網站中的位置如何。 根據Express的API,我已經使用過了

app.all("*", doSomething);

在每個頁面加載時調用doSomething函數,但它並不完全有效。 該函數會在每個頁面加載時觸發,除了基本域的頁面加載(例如http://domain.com/pageA將調用該函數,但http://domain.com不會)。 有誰知道我做錯了什么?

謝謝!

我知道這是一個舊的,但仍然可能對某人有用。

我認為問題可能是:

app.use(express.static(path.join(__dirname, 'public')));

var router = express.Router();

router.use(function (req, res, next) {
    console.log("middleware");
    next();
});

router.get('/', function(req, res) {
    console.log('root');
});
router.get('/anything', function(req, res) {
   console.log('any other path');
});

在任何路徑上調用中間件的位置,但/

這是因為默認情況下express.static在/上提供public/index.html

要解決此問題,請將參數添加到靜態中間件:

app.use(express.static(path.join(__dirname, 'public'), {
    index: false
}));

我打賭你放了

app.get('/', fn)

以上

app.all("*", doSomething);

請記住,Express將按照注冊順序執行中間件功能,直到某些內容發送響應為止

如果要在每個請求上運行一些代碼,則不需要使用路由器。

只需將中間件放在路由器上方,每次請求都會調用它:

app.use(function(req, res, next){
  //whatever you put here will be executed
  //on each request

  next();  // BE SURE TO CALL next() !!
});

希望這可以幫助

鏈中的app.all('*')在哪里? 如果它在所有其他路由之后,則可能不會被調用。

app.post("/something",function(req,res,next){ ...dothings.... res.send(200); });

app.all('*',function(req,res) { ...this NEVER gets called. No next and res already sent });

除非你打算讓它成為最后一個,否則你必須確保在前面的路線中調用next()。 例如:

app.post("/something",function(req,res,next){ ...dothings.... next();});

app.all('*',function(req,res) { ...this gets called });

還有什么在doSomething? 你確定它沒有被調用嗎?

我也有這個問題,我發現你的doSomething函數的參數數量可能是一個因素。

function doSomething(req, res, next) {
    console.log('this will work');
}

然而:

function doSomething(req, res, next, myOwnArgument) {
    console.log('this will never work');
}

暫無
暫無

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

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