我正在尝试使用 node-rest-client 从节点调用 REST API。如果我的调用返回错误,我想捕获错误并将其报告给调用者。
我正在用 Postman 尝试这个,不幸的是这只能工作一次。当我第二次按发送时,我的 node.js 程序崩溃并出现错误“发送后无法设置标题”。
我是 node.js 的新手,因此非常感谢任何帮助!
//app stuff
const client_id = "x";
const client_secret = "y";
const callback = "https://myurl;
// Basic Setup
var http = require('http'),
express = require('express'),
mysql = require('mysql'),
parser = require('body-parser'),
Client = require('node-rest-client').Client;
var client = new Client();
// Setup express
var app = express();
app.use(parser.json());
app.use(parser.urlencoded({ extended: true }));
app.set('port', process.env.PORT || 5000);
// Set default route
app.get('/', function (req, res) {
res.send('<html><body><p>Welcome to Bank API Wrapper</p></body></html>');
});
app.post('/authorize', function (req,res) {
var response = [];
if (typeof req.body.code !== 'undefined' && typeof req.body.state !== 'undefined' ){
var code = req.body.code, state = req.body.state;
//conversion to base64 because citi api wants it this way
var authorization = "Basic " + Buffer.from(client_id + ":" + client_secret).toString('base64');
var args = {
data:{"grant_type":"authorization_code","code":code,"redirect_uri":callback},
headers:{"Authorization":authorization,"Content-Type":"application/x-www-form-urlencoded"}
};
//get access and refresh token
client.post("https://sandbox.apihub.citi.com/gcb/api/authCode/oauth2/token/sg/gcb", args, function (citidata, citiresponse) {
//console.log(citidata);
//console.log(citiresponse);
});
client.on('error', function (err) {
response.push({'result' : 'error', 'msg' : 'unauthorized access'});
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
});
}
else {
response.push({'result' : 'error', 'msg' : 'Please fill required details'});
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
}
});
// Create server
http.createServer(app).listen(app.get('port'), function(){
console.log('Server listening on port ' + app.get('port'));
});