-->

How add new method in response and request

2019-05-25 03:26发布

问题:

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

回答1:

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


回答2:

Add methods to express.response object:

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