res.writeHead覆盖不起作用

时间:2017-04-07 23:52:46

标签: node.js overrides

我正在尝试覆盖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。为什么呢?

1 个答案:

答案 0 :(得分:1)

当您致电_writeHead时,this对象未引用res。它引用全局上下文,阻止Node.js正常运行。将const _writeHead = res.writeHead;更改为const _writeHead = res.writeHead.bind(res);