Monkeypatch 重新发送

Osc*_*Ryz 0 javascript node.js express

来自大学的建议并遵循这个答案

我正在尝试猴子修补 res.send 但出现以下错误:

TypeError: Cannot read property 'req' of undefined
Run Code Online (Sandbox Code Playgroud)

这是我的代码

const express = require('express')
const app = express()

app.use((req, res, next ) => {
    const oldSend = res.send;
    res.send = (data) => {
        console.log(data.length);
        oldSend(data);
    }
    next();
})
app.get('/', (req, res) => res.send('Hello World!'))
Run Code Online (Sandbox Code Playgroud)

完整的堆栈跟踪:

Example app listening on port 3000!
undefined
TypeError: Cannot read property 'req' of undefined
    at send (/Users/code/js/hello/node_modules/express/lib/response.js:110:17)
    at ServerResponse.res.send (/Users/code/js/hello/index.js:8:9)
    at app.get (/Users/code/js/hello/index.js:12:32)
    at Layer.handle [as handle_request] (/Users/code/js/hello/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/code/js/hello/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/code/js/hello/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/code/js/hello/node_modules/express/lib/router/layer.js:95:5)
    at /Users/code/js/hello/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/code/js/hello/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/code/js/hello/node_modules/express/lib/router/index.js:275:10)
Run Code Online (Sandbox Code Playgroud)

其中第 110 行是:

res.send = function send(body) {
  var chunk = body;
  var encoding;
  var req = this.req; //<-- THIS 
  var type;

  // settings
  var app
....
Run Code Online (Sandbox Code Playgroud)

Lau*_*rin 5

这是因为 JavaScript 中的方法并不与其实例相关联。

如果您a.fun()在函数代码内调用 ,this则最初将设置为a。但发生这种情况只是因为a出现在方法调用中:fun否则是与 没有关系的任意函数a

在你的情况下,这应该有效:

oldSend.call(res, data);
Run Code Online (Sandbox Code Playgroud)

的要点call()是设置this