我是这样做的,覆盖request module 中的一种方法。 警告:许多节点模块的扩展设计不佳,包括请求,因为它们在构造函数中做了太多的事情。不仅仅是一个庞大的参数选项,而是启动 IO、连接等。例如,请求将 http 连接(最终)作为构造函数的一部分。没有明确的.call() 或.goDoIt() 方法。
在我的示例中,我想使用查询字符串而不是 qs 来格式化表单。我的模块被巧妙地命名为“MyRequest”。在名为 myrequest.js 的单独文件中,您有:
var Request = require('request/request.js');
var querystring = require('querystring');
MyRequest.prototype = Object.create(Request.prototype);
MyRequest.prototype.constructor = MyRequest;
// jury rig the constructor to do "just enough". Don't parse all the gazillion options
// In my case, all I wanted to patch was for a POST request
function MyRequest(options, callbackfn) {
"use strict";
if (callbackfn)
options.callback = callbackfn;
options.method = options.method || 'POST'; // used currently only for posts
Request.prototype.constructor.call(this, options);
// ^^^ this will trigger everything, including the actual http request (icky)
// so at this point you can't change anything more
}
// override form method to use querystring to do the stringify
MyRequest.prototype.form = function (form) {
"use strict";
if (form) {
this.setHeader('content-type', 'application/x-www-form-urlencoded; charset=utf-8');
this.body = querystring.stringify(form).toString('utf8');
// note that this.body and this.setHeader are fields/methods inherited from Request, not added in MyRequest.
return this;
}
else
return Request.prototype.form.apply(this, arguments);
};
然后,在您的应用程序中,而不是
var Request = require("request");
Request(url, function(err, resp, body)
{
// do something here
});
你去
var MyRequest = require("lib/myrequest");
MyRequest(url, function(err, resp, body)
{
// do that same something here
});
我不是 JavaScript 专家,所以可能有更好的方法...