javascript - 我应该在 Sails.js 中的哪里扩展 ServerResponse 原型(prototype)?

标签 javascript node.js sails.js

  • Sails.js v0.9.4
  • Node.js v0.10.18
  • Express.js v3.2.6

我编写了 sails 简单的 Web 应用程序。 我想向 ServerResponse 原型(prototype)添加新函数,以实现如下所示的常见错误响应。

UtilService.js

require('http').ServerResponse.prototype.returnError = function (message) {
    console.error("Error: " + message);
    return this.view("./error", { errors: [{ stack: message }] });
};

FooController.js

require("../services/UtilService");

以上代码运行良好。但我不会向所有 Controller 编写相同的代码片段。 我怎样才能保持干燥?换句话说,我应该在哪个文件中编写上面的扩展代码?


添加于 2013-09-25 09:26 UTC

感谢您的意见和建议。 我在 config/bootstrap.js 中添加了特殊逻辑,因为我只想运行原型(prototype)修改代码一次。 这看起来工作正常。

配置/bootstrap.js

module.exports.bootstrap = function (cb) {
  cb();
  require('http').ServerResponse.prototype.returnError = function (message) {
    console.error("Error: " + message);
    return this.view("./error", { errors: [{ stack: message }] });
  };
};

最佳答案

感谢您的意见和建议。我在 config/bootstrap.js 中添加了特殊逻辑,因为我只想运行原型(prototype)修改代码一次。这看起来工作正常。

配置/bootstrap.js

module.exports.bootstrap = function (cb) {
  cb();
  require('http').ServerResponse.prototype.returnError = function (message) {
    console.error("Error: " + message);
    return this.view("./error", { errors: [{ stack: message }] });
  };
};

关于javascript - 我应该在 Sails.js 中的哪里扩展 ServerResponse 原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18975491/

相关文章:

javascript - 如何从 route 获取 Express 中的本地人

javascript - 如何为 Node.js 中的 post 模块修复 "ReferenceError: xxx is not defined"

javascript - 从 Javascript 函数内传递值

javascript - 尝试获取 API 提供的 javascript 对象的“名称”

javascript - 在 Sails 中访问 JSON 请求参数

node.js - Sails 0.10 ModelIdentity.subscribe 或 .watch 和 publishCreate()?

javascript - 如何在 sails.js 中使用 gruntfile.js 缩小所有 js 和 css 文件

sails.js - 如何使用 Treeline 创建新的服务器端 View ?

javascript - 正弦球动画 CSS3

javascript - Typescript class.default 不是构造函数