我正在尝试覆盖Node.js中的res.writeHead
方法,尽管它会抛出错误。这是代码:
const http = require('http');
http.createServer((req, res) => {
const _writeHead = res.writeHead;
res.writeHead = (...a) => {
console.log('res.writeHead called!');
_writeHead(...a);
};
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Hello, world!');
}).listen(2020);
记录 res.writeHead called!
,然后在客户端连接时获得TypeError: Cannot read property 'statusMessage' of undefined
。为什么呢?
答案 0 :(得分:1)
当您致电_writeHead
时,this
对象未引用res
。它引用全局上下文,阻止Node.js正常运行。将const _writeHead = res.writeHead;
更改为const _writeHead = res.writeHead.bind(res);
。