- 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/