Node.js:如何对 Express 中的所有 HTTP 请求执行某些操作? [英] Node.js : How to do something on all HTTP requests in Express?

查看:24
本文介绍了Node.js:如何对 Express 中的所有 HTTP 请求执行某些操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想做类似的事情:

So I would like to do something like:

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

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

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..

在普通的 node.js 中,就像在我们创建 http 服务器之后,在我们进行页面路由之前编写任何东西一样简单.

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

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

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

推荐答案

Express 基于 Connect 中间件.

Express is based on the Connect middleware.

Express 的路由功能由您应用的router 提供,您可以自由地将自己的中间件添加到您的应用中.

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.

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:如果您只想要一些日志记录,您可以考虑使用 logger 由 Connect 提供)

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

这篇关于Node.js:如何对 Express 中的所有 HTTP 请求执行某些操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆