簡體   English   中英

Node.js:如何處理 Express 中的所有 HTTP 請求?

[英]Node.js : How to do something on all HTTP requests in Express?

所以我想做一些類似的事情:

app.On_All_Incoming_Request(function(req, res){
    console.log('request received from a client.');
});

當前的app.all()需要一個路徑,如果我給出這個/例子,那么它只在我在主頁上時才有效,所以它並不是全部..

在普通的 node.js 中,它就像在我們創建 http 服務器之后、在我們進行頁面路由之前編寫任何東西一樣簡單。

那么如何用 express 做到這一點,最好的方法是什么?

Express 基於Connect中間件。

Express 的路由功能由您的應用程序的router提供,您可以自由地將自己的中間件添加到您的應用程序中。

var app = express.createServer();

// Your own super cool function
var logger = function(req, res, next) {
    console.log("GOT REQUEST !");
    next(); // Passing the request to the next handler in the stack.
}

app.configure(function(){
    app.use(logger); // Here you add your logger to the stack.
    app.use(app.router); // The Express routes handler.
});

app.get('/', function(req, res){
    res.send('Hello World');
});

app.listen(3000);

就這么簡單。

(PS:如果您只是想要一些日志記錄,您可以考慮使用 Connect 提供的記錄器

你應該做這個:

app.all("*", function (req, resp, next) {
   console.log(req); // do anything you want here
   next();
});

你可以通過引入一個中間件功能來實現。 app.use(your_function) 可以提供幫助。 app.use 與接受一個函數,該函數將在記錄到您服務器的每個請求上執行。 例子:

app.use((req,res,next)=>{
console.log('req recieved from client');
next();//this will invoke next middleware function
})

Express 支持路由路徑中的通配符 所以app.all('*', function(req, res) {})是一種方法。

但這僅適用於路由處理程序。 不同之處在於 Express 路由處理程序應該發送響應,如果沒有,Express 將永遠不會發送響應。 如果您想在不顯式發送響應的情況下執行某些操作,例如檢查標頭,則應使用Express 中間件 app.use(function(req, res, next) { doStuff(); next(); }

暫無
暫無

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

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