Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我应该在哪里扩展Sails.js中的ServerResponse原型? Sails.js v0.9.4 Node.js v0.10.18 Express.js v3.2.6_Javascript_Node.js_Sails.js - Fatal编程技术网

Javascript 我应该在哪里扩展Sails.js中的ServerResponse原型? Sails.js v0.9.4 Node.js v0.10.18 Express.js v3.2.6

Javascript 我应该在哪里扩展Sails.js中的ServerResponse原型? Sails.js v0.9.4 Node.js v0.10.18 Express.js v3.2.6,javascript,node.js,sails.js,Javascript,Node.js,Sails.js,我已经编写了sails简单的web应用程序。 我想向ServerResponseprototype添加新函数,以实现如下常见错误响应 UtilService.js FooController.js 以上代码运行良好。但我并不是对所有控制器都编写相同的代码段。 我怎样才能保持干燥?换句话说,上面的扩展代码应该写哪个文件 于2013-09-25 09:26 UTC时添加 谢谢你的建议和建议。 我在config/bootstrap.js中添加了特殊的逻辑,因为我只想运行一次原型修改代码。 这看起来很

我已经编写了sails简单的web应用程序。 我想向
ServerResponse
prototype添加新函数,以实现如下常见错误响应

UtilService.js FooController.js 以上代码运行良好。但我并不是对所有控制器都编写相同的代码段。 我怎样才能保持干燥?换句话说,上面的扩展代码应该写哪个文件


于2013-09-25 09:26 UTC时添加
谢谢你的建议和建议。 我在
config/bootstrap.js
中添加了特殊的逻辑,因为我只想运行一次原型修改代码。 这看起来很好用

config/bootstrap.js
这似乎是一个使用策略的好地方,因为像六氰化物所建议的那样“从根本上”扩展原型需要修改express中间件,我认为这是不推荐的

相反,在
config/policies.js
中,尝试向所有操作添加默认策略,例如:

someController: {
  '*': httpPrototype
}
httpPrototype策略可以如下所示:

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

谢谢你的建议和建议。我在
config/bootstrap.js
中添加了特殊的逻辑,因为我只想运行一次原型修改代码。这看起来很好用

config/bootstrap.js
谢谢你的建议!我想避免每次请求都执行,所以我修改了
config/bootstrap.js
。但是你关于
policies.js
的建议对我来说真的很有价值。你能在另一个答案中分享你的实现并接受它吗?这样,未来的读者可以从您的经验中受益。当我只有一个简单的http.Server(没有任何像sails或express这样的框架)时,您知道如何扩展ServerResponse原型吗。
module.exports.bootstrap = function (cb) {
  cb();
  require('http').ServerResponse.prototype.returnError = function (message) {
    console.error("Error: " + message);
    return this.view("./error", { errors: [{ stack: message }] });
  };
};
someController: {
  '*': httpPrototype
}
module.exports = function httpPrototype (req, res, next) {
  require('http').ServerResponse.prototype.returnError = function (message) {
    console.error("Error: " + message);
    return this.view("./error", { errors: [{ stack: message }] });
  };
  next();
};
module.exports.bootstrap = function (cb) {
  cb();
  require('http').ServerResponse.prototype.returnError = function (message) {
    console.error("Error: " + message);
    return this.view("./error", { errors: [{ stack: message }] });
  };
};