gpt4 book ai didi

javascript - Monkeypatch 重新发送

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:52 24 4
gpt4 key购买 nike

来自大学的建议和关注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
....

最佳答案

这是因为方法不与其 JavaScript 中的实例绑定(bind)。

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

就您而言,这应该有效:

oldSend.call(res, data);

call() 的要点是设置 this

关于javascript - Monkeypatch 重新发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49183906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com