【发布时间】:2016-01-11 23:57:28
【问题描述】:
我在节点客户端上使用superagent 来触发POST 或PATCH 这样的请求(太丑了!):
if-else 中的两个代码块之间的唯一区别是 http verb 和 API 端点,在 patch 请求的情况下,URL 还附加了一个 /:id。
if ( typeof resourceId === 'undefined' ){
request
.post('http://localhost:8080/api/resources/')
.send(JSON.stringify(resource_json))
.set('Accept', 'application/json')
.set('Content-Type', 'application/json')
.set('Authorization', 'Token token=3S4pREbMkMoEGG6zHeUJ7Qtt')
.end(function(err, res) {
if (!err && res.ok) {
console.log(chalk.bold.cyan('Resource created successfully'));
packageJson.resource_id = res.body.id;
fs.writeFileSync('package.json', JSON.stringify(packageJson));
process.exit(0);
}
var errorMessage;
if (res && res.status === 401) {
errorMessage = "Authentication failed! Bad username/password?";
} else if (err) {
errorMessage = err;
} else {
errorMessage = res.text;
}
console.error(chalk.red(errorMessage));
process.exit(1);
});
} else {
request
.patch('http://localhost:8080/api/reources/' + resourceId)
.send(JSON.stringify(resource_json))
.set('Accept', 'application/json')
.set('Content-Type', 'application/json')
.set('Authorization', 'Token token=3S4pREbMkMoEGG6zHeUJ7Qtt')
.end(function(err, res) {
if (!err && res.ok) {
console.log(chalk.bold.cyan('Resource created successfully'));
packageJson.book_id = res.body.id;
fs.writeFileSync('package.json', JSON.stringify(packageJson));
process.exit(0);
}
var errorMessage;
if (res && res.status === 401) {
errorMessage = "Authentication failed! Bad username/password?";
} else if (err) {
errorMessage = err;
} else {
errorMessage = res.text;
}
console.error(chalk.red(errorMessage));
process.exit(1);
});
}
我怎样才能把它弄干?
【问题讨论】:
标签: node.js superagent