// VCAP_SERVICE에서 앱과 바인드한 서비스 정보를 가져온다.
// 복수의 서비스가 앱에 바인드 될 수 있다.
vcapBindServices = vcapService[Object.keys(vcapService)[0]];
var sampleApiCaller = function sampleApiCaller() {
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', accessControlAllowHeader);
// 뷰에서 참조하는 js 모듈을 미들웨어에 마운트 한다.
app.use('/bower_components',
express.static(__dirname + '/bower_components'));
// 웹 서비스 메인을 미들웨어에 마운트 한다.
app.get('/', function(req, res) {
res.render('apiCaller'); // 뷰 생성
// to support JSON-encoded bodies
app.use(bodyParser.json());
// to support URL-encoded bodies
app.use(bodyParser.urlencoded({
app.post('/sampleApiSerivceCall', function(req, res, next) {
if (typeof vcapBindServices !== 'object') {
return res.status(502).send('unbind service called');
// API Service와 연동 할 서비스를 구한다.
// 바인드된 복수의 서비스 중에서 연동 할 서비스 정보를 구한다.
var bindApiService = vcapBindServices[0];
// 위에서 구한 서비스 정보에서 서비스 url를 구한다.
var serviceUrl = bindApiService.credentials.uri ?
bindApiService.credentials.uri : bindApiService.credentials.url;
// API Service에 요청 할 JSON 을 작성한다.
var callEvent = buildSendData(req.body, bindApiService);
// api Service에 요청하고 결과를 응답한다.
request.post(options, function(error, response, body) {
if (error) console.log(error);
else if (response.statusCode === 201 || response.statusCode === 200) {
// console.log('Successfully reported usage %j with headers %j',
// usage, response.headers);
res.status(201).send(response.body);
// console.log('failed report usage %j with headers %j',
// usage, response.headers);
res.sendStatus(response.statusCode);
app.use(function(req, res) {
res.send('404 not found');