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

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

问题描述

所以我想做一些例子:

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

那么如何用快递来做这个,什么是最好的方法呢?

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的路由功能由路由器提供您的应用程序,您可以自由添加自己的应用程序。

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

这很简单。

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

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

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

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