【问题标题】:Addition of new methods to node.js http.ServerResponse.prototype not working向 node.js http.ServerResponse.prototype 添加新方法不起作用
【发布时间】:2017-09-28 13:53:57
【问题描述】:

作为我学习 Node 内部结构的一部分,我正在尝试向 Node 响应原型添加一些基本功能,而不需要一些外部库。这应该不是一项艰巨的任务,但是,响应永远不会传递给新函数,也永远无法通过 this 语句检索。这是一个将模板渲染函数绑定到服务器响应的示例。

const http = require('http');

const newMethods = Object.create(http.ServerResponse.prototype);

newMethods.render = async (view, data) => {
    const renderResult = await aTemplateLibray(view, data);
    this.writeHead(200, {'Content-Type': 'text/html'});
    this.end(renderResult);
}
// Other methods here...

// Then
Object.assign(http.ServerResponse.prototype, newMethods);

module.exports = http;

一旦我使用了这个http服务器,我就可以使用新的渲染函数,但是响应没有传递给它,所以会抛出一个错误信息,比如this.writeHead is not a function .

我也尝试过 Object.defineProperty 方法。

Object.defineProperty(http.ServerResponse.prototype, 'render', 
    {writable: true,
     enumerable: true,
     get: return this.socket.parser.incoming
    });

我找到了一些旧库,它使用旧的 __defineGetter__ 方法返回了那个套接字,我用新的形式对其进行了测试,但它也不起作用。

【问题讨论】:

  • 第一个版本没有多大意义(创建对象,添加属性,然后复制该属性到原型没有意义),此外使用箭头函数,所以this 当然不是你所期望的(更多在this question,虽然在某处有更好的)。 defineProperty 版本甚至不会解析。

标签: javascript node.js http prototype middleware


【解决方案1】:

主要问题是您使用箭头函数表达式 (=>),这对于函数内部的 this 指向的内容具有特殊的影响(更多关于 here)。

在你的情况下,你想使用async function(...):

newMethods.render = async function(view, data) {
    const renderResult = await aTemplateLibray(view, data);
    this.writeHead(200, {'Content-Type': 'text/html'});
    this.end(renderResult);
}

【讨论】:

    猜你喜欢
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多