How add new method in response and request

点点圈 提交于 2019-12-06 11:09:57

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

Add methods to express.response object:

const express = require('express');
express.response.getName = () => { return 'Alice' };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!