如何在响应和请求中添加新方法 [英] How add new method in response and request

查看:137
本文介绍了如何在响应和请求中添加新方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在node.js的响应和请求中添加新方法。



我如何更有效地做到这一点?



我无法理解在express.js中如何做到这一点

解决方案

作为JavaScript,有很多方法可以做到这一点。对于express来说,对我来说最合理的模式是将函数添加到早期中间件中的每个请求实例:

  //只是一个例子
函数getBrowser(){
返回this.get('User-Agent');
}

app.use(函数(req,res,next){
req.getBrowser = getBrowser;
next();
}) ;

app.get('/',function(req,res){
//你可以在这里调用req.getBrowser()
});

在express.js中,这是通过向http.IncomingMessage的原型添加附加功能来完成的。 / p>

https ://github.com/visionmedia/express/blob/5638a4fc624510ad0be27ca2c2a02fcf89c1d334/lib/request.js#L18



这有时被称为猴子修补或自由修补。关于这是奇妙还是可怕,意见各不相同。我上面的方法更谨慎,更不可能对node.js进程中运行的其他代码造成干扰。添加你自己的:

  var http = require('http'); 
http.IncomingMessage.prototype.getBrowser = getBrowser; //你的自定义方法


I want to add new method in response and request of node.js.

How i can do it more efficiently?

I can't understand how this is done in express.js

解决方案

Being JavaScript, there are numerous ways to do this. The pattern that seems most reasonable to me for express is to add the function to each request instance in an early middleware:

//just an example
function getBrowser() {
    return this.get('User-Agent'); 
}

app.use(function (req, res, next) {
  req.getBrowser = getBrowser;
  next();
});

app.get('/', function (req, res) {
    //you can call req.getBrowser() here
});

In express.js, this is done by adding additional function to the prototype of http.IncomingMessage.

https://github.com/visionmedia/express/blob/5638a4fc624510ad0be27ca2c2a02fcf89c1d334/lib/request.js#L18

This is sometimes called "monkey patching" or "freedom patching". Opinions vary on whether this is fantastic or terrible. My approach above is more prudent and less likely to cause intended interference with other code running inside your node.js process. To add your own:

var http = require('http');
http.IncomingMessage.prototype.getBrowser = getBrowser; //your custom method

这篇关于如何在响应和请求中添加新方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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