【发布时间】:2015-11-10 00:04:24
【问题描述】:
我有一个简单的 http 客户端模块 (api.js),它返回如下所示的承诺:
exports.endpoint = '';
exports.GET = function(args){
args.method = 'GET';
args.uri = this.endpoint + args.uri;
return asyncApiCall(args);
};
exports.POST = function(args){
args.method = 'POST';
args.uri = this.endpoint + args.uri;
return asyncApiCall(args);
};
exports.PUT = function(args){
args.method = 'PUT';
args.uri = this.endpoint + args.uri;
return asyncApiCall(args);
};
exports.DELETE= function(args){
args.method = 'DELETE';
args.uri = this.endpoint + args.uri;
return asyncApiCall(args);
};
var asyncApiCall = function(args){
var rp = require('request-promise');
var options = {
method: args.method,
uri: args.uri,
body : args.body,
json: args.json
}
return rp(options);
};
我使用这样的模块:
var api = require('./api.js');
var args = {
uri : '/posts'
}
api.endpoint = 'http://localhost:3000';
api.GET(args)
.then(function(res){
console.log(res);
}, function(err){
console.log(err);
});
现在,我想尽可能地改进模块。有什么办法不重复export.functionName?我在 NodeJS 中找到了 module.exports,但我不确定在这种情况下如何使用它。如何在 asyncApiCall 函数中设置端点变量一次,而不是在所有其他返回 asyncApiCall 的函数中设置?
【问题讨论】:
标签: javascript node.js httpclient