Node.js:如何对Express中的所有HTTP请求执行某些操作?

时间:2021-11-18 22:45:37

So I would like to do something like:

所以我想做一些事情:

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

the current app.all() requires a path, and if I give for example this / then it only works when I'm on the homepage, so it's not really all..

当前的app.all()需要一个路径,如果我举例说明这个/那它只有当我在主页上时才有效,所以它并不是全部......

In plain node.js it is as simple as writing anything after we create the http server, and before we do the page routing.

在plain node.js中,它就像在创建http服务器之后,在我们进行页面路由之前编写任何内容一样简单。

So how to do this with express, and what is the best way to do it?

那么如何用express来做到这一点,最好的方法是什么?

1 个解决方案

#1


44  

Express is based on the Connect middleware.

Express基于Connect中间件。

The routing capabilities of Express are provided by the router of your app and you are free to add your own middlewares to your application.

Express的路由功能由您的应用程序的路由器提供,您可以*地将自己的中间件添加到您的应用程序中。

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);

It's that simple.

就这么简单。

(PS : If you just want some logging you might consider using the logger provided by Connect)

(PS:如果你只想要一些日志记录,你可以考虑使用Connect提供的记录器)

#1


44  

Express is based on the Connect middleware.

Express基于Connect中间件。

The routing capabilities of Express are provided by the router of your app and you are free to add your own middlewares to your application.

Express的路由功能由您的应用程序的路由器提供,您可以*地将自己的中间件添加到您的应用程序中。

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);

It's that simple.

就这么简单。

(PS : If you just want some logging you might consider using the logger provided by Connect)

(PS:如果你只想要一些日志记录,你可以考虑使用Connect提供的记录器)