如何在响应和请求中添加新方法

时间:2013-09-15 19:37:42

标签: javascript node.js prototypal-inheritance

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

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

我无法理解在express.js

中如何做到这一点

2 个答案:

答案 0 :(得分:6)

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

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

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

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

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

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

答案 1 :(得分:0)

添加方法来表达对象。

const express = require('express');
express.response.getName = () => { return 'Alice' };