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

标签 javascript node.js express prototypal-inheritance

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

我怎样才能更有效地做到这一点?

我不明白这是如何在 express.js 中完成的

最佳答案

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

//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 的原型(prototype)添加额外的函数来完成的。

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

关于javascript - 如何在响应和请求中添加新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18816685/

相关文章:

javascript - 忽略字符串的第一个字符 - JS - 正则表达式

javascript - 设置 select2 输入的默认值

Node.js 通过查询字符串传递参数

node.js - aws lambda 调用未在 POST 上填充正文

node.js - Heroku ENOENT : no such file or directory due to faulty express. js 路由

javascript - 将 Node 变量从 Jade 传递到包含的 html?

javascript - 环回。如何获得一个用户的所有角色?

javascript - struts2中如何通过ajax上传文件

javascript - 是否可以从响应式图像路径的末尾删除尺寸?

javascript - HTML 分页问题