title: How to properly call an external api to use from within express application to build my own restful api?
body: <p>I'am trying to create a restful api but I need to use an external api quandl to build my api, when i try to use my api from the client(built in angularjs) i get a 500 internal server error and No default engine was specified and no extension was provided in command line. i know my api work cause i tested it with postman, its just not working from the client.
  I tried looking at this post : <a href="https://stackoverflow.com/questions/23296031/express-js-4-how-to-serve-json-results-without-rendering-any-views-css">express js 4 how to serve json results without rendering any views /css</a> but it wasnt helpful.</p>
  
  <pre><code>module.exports = function(io){
      var q = require('q');
      var request = require('request');
      var mongoose = require('mongoose');
      var Stock = mongoose.model('Stock');
      var base_url = "https://www.quandl.com/api/v3/datasets/WIKI/";
      var dotjson = ".json" 
      var apiKey = "?api_key=" + process.env.quandl_apiKey;
  
      function sendJsonResponse(res,status,content){
          res.status(status);
          res.json(content);
      }
  
      // get stock data using quandl api  
      function stockData(name){
          var deferred = q.defer();
          var d = new Date();
          var year = d.getFullYear();
          var month = d.getMonth() + 1;
          var date = d.getDate();
  
          request({
              url: base_url + name + dotjson + apiKey,
              qs:{
                  start_date:(year-1) + '-' + month + '-' + date,
                  end_date:year + '-' + month + '-' + date
              }
          },function(error,response,body){
              if(error){
                  deferred.reject('Error: ' + error);
              }else if(response.statusCode !== 200){
                  deferred.reject('Invalid Status Code: ' + response.statusCode);
              }else{
                  deferred.resolve(body);
              }
  
          })
  
          return deferred.promise;
      }
  
      // get stock data that is stored in database
      function getStockInDatabase(req,res){
          Stock.find({},function(err,stock){
              if(err){
                  sendJsonResponse(res,404,err);
              } else {
                  sendJsonResponse(res,200,stock);
              }
          })
      }
  
      // create stock data to be stored in database
      function createStockData(req,res){
          var stockDatas;
          stockData(req.body.name.toUpperCase())
                 .then(function(stock){
                    stockDatas = JSON.parse(stock);
                    Stock.create({
                      name:stockDatas.dataset.name,
                      symbol:stockDatas.dataset.dataset_code
                    },function(err,stk){
                      if(err){
                          sendJsonResponse(res,400,err)
                      }else{
                          sendJsonResponse(res,201,stk);
                          io.emit('stock',stockDatas);
                      }
                    })
                 })
                .catch(function(err){
                  sendJsonResponse(res,404,err);
                })
      } 
  
      // delete stock data in database
      function deleteStockData(req,res){
          Stock
              .findByIdAndRemove(req.body._id)
              .exec(function(err,stock){
                      if(err){
                          sendJsonResponse(res,404,err);
                      }else {
                          sendJsonResponse(res,204,null);
                      }
              })
      } 
  
      return {
          getStockInDatabase:getStockInDatabase,
          createStockData:createStockData,
          deleteStockData:deleteStockData
      }
  }
  </code></pre>
  
  <p>angular service to use api:</p>
  
  <pre><code>  (function(){
     'use strict'
      angular
       .module('app.common')
       .factory('stockService',stockService);
  
       stockService.$inject = ['$http'];
  
       function stockService($http){
  
          function getStock(){
              return $http.get('/api/stocks');
          } 
  
          function getStockInDatabase(){
              return $http.get('api/stocks/database');
          }
  
          function createStock(data){
              return $http.post('/api/stocks',data);
          }
  
          function deleteStock(data){
              return $http.delete('/api/stocks',data);
          }
  
          return{
              getStockInDatabase:getStockInDatabase,
              createStock:createStock,
              deleteStock:deleteStock
          }
  
       }
  })()
  </code></pre>
  
  <p>app.js configuration</p>
  
  <pre><code>require('dotenv').load();
  var express = require('express');
  var socketio = require('socket.io');
  var path = require('path');
  var logger = require('morgan');
  var cookieParser = require('cookie-parser');
  var bodyParser = require('body-parser');
  var io = socketio();
  require('./api/models/db'); 
  
  var app = express();
  app.io = io;
  var apiRoute = require('./api/routes/index')(io);
  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(express.static(path.join(__dirname, 'client')));
  
  app.use('/api', apiRoute);
  
  app.use(function(req, res) {
    res.sendFile(path.join(__dirname, 'client', 'index.html'));
  });
  
  // catch 404 and forward to error handler
  app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
   next(err);
  });
  
  // error handlers
  
  // development error handler
  // will print stacktrace
  if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
     res.status(err.status || 500);
     res.render('error', {
     message: err.message,
     error: err
     });
    });
  }
  
  // production error handler
  // no stacktraces leaked to user
  app.use(function(err, req, res, next) {
    res.status(err.status || 500).send({
    message: err.message,
    error: {}
   })
  });
  
  
  module.exports = app;
  </code></pre>