Monkeypatch res.send

时间:2018-03-08 22:58:56

标签: javascript node.js express

从大学建议开始,跟随this answer

我试图修补补丁res.send,但我收到以下错误:

TypeError: Cannot read property 'req' of undefined

这是我的代码

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!'))

完整的堆栈跟踪:

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)

第110行是:

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

  // settings
  var app
....

2 个答案:

答案 0 :(得分:3)

因为方法与JavaScript中的实例无关。

如果您在功能代码中致电a.fun()this最初将设为a。但这只是因为a出现在方法调用中而发生:fun是一个与a无关的任意函数。

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

oldSend.call(res, data);

call()的目的是设置this

答案 1 :(得分:0)

找到解决方案,oldSend失去了它的上下文(?)

如果我添加const oldSend = res.send.bind(res);

{{1}}

问题已经消失。