title: Node.js + express - retrieving server-side data at the client
body: <p>New to Node.js and am slowly piecing things together from a number of tutorials and other posts here on the site.</p>
  
  <p>Presently, I am attempting to make an API request by means of the https module, and use a value returned (an authentication token) in the client for a lightweight example.</p>
  
  <p>My current attempt is very simple - a client-side js function is called on a button press, which makes an Ajax call to a node server router.</p>
  
  <p>The problem that I am having is that I cannot seem to retrieve data from the server at the client. This may be an issue of event-handling or some asynchronous behavior that I'm not fully understanding - the value I'm trying to retrieve can be seen in the <code>login()</code> function that I call. Specifically, I see this token in the <code>data</code> value that I am writing out to the console (see <code>api.js</code>)  Does anything from my current approach stand out as glaringly wrong?</p>
  
  <p>Thank you in advance for any help you might be able to offer.</p>
  
  <p>For context, App.js is where I am storing this route, as well as starting the server. I am then making use of the api.js module by means of an ajax call from client.js.</p>
  
  <p><a href="https://i.stack.imgur.com/scfXv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/scfXv.png" alt="project layout"></a></p>
  
  <pre><code>//app.js
  var express = require('express');
  var app = express();
  var api = require('./public/api.js');
  
  app.post('/login', function(req, res) {
      //token has no value currently, but along the lines of what I'm hoping to accomplish
      var token = api.login();        
      res.end(token);
  });
  
  app.use(express.static(__dirname + '/public'));
  
  var server = app.listen(9001, function() {
      console.log('Listening on port 9001');
  });
  </code></pre>
  
  <p>&nbsp;</p>
  
  <pre><code>//api.js (node module)
  var exports = module.exports = {};
  var querystring = require('querystring');
  var https = require('https');
  
  var host = 'api.robinhood.com';
  var username = '[username here]';
  var password = '[password here]';
  var response = null;
  
  function performRequest(endpoint, method, data, success) {
    var dataString = JSON.stringify(data);
    var headers = {};
  
    if (method == 'GET') {
      endpoint += '?' + querystring.stringify(data);
    }
    else {
      headers = {
        'Content-Type': 'application/json',
        'Content-Length': dataString.length
      };
    }
    var options = {
      host: host,
      path: endpoint,
      method: method,
      headers: headers
    };
  
    var req = https.request(options, function(res) {
      res.setEncoding('utf-8');
  
      var responseString = '';
  
      res.on('data', function(data) {
        responseString += data;
      });
  
      res.on('end', function() {
        var responseObject = JSON.parse(responseString);
        success(responseObject);
      });
    });
  
    req.write(dataString);
    req.end();
  }
  
  exports.login = function() {
    return performRequest('/api-token-auth/', 'POST', {
      username: username,
      password: password
    }, function(data) {
      sessionId = data.token;
      console.log('Logged in:', sessionId);
    });
  }
  </code></pre>
  
  <p>&nbsp;</p>
  
  <pre><code>&lt;!-- index.html --&gt;
  &lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;script type="text/javascript" src="jquery-1.12.4.min.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript" src="client.js"&gt;&lt;/script&gt;
  &lt;head&gt;
      &lt;title&gt;Making API Calls!&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;button id="login"&gt;Log in&lt;/button&gt;
      &lt;hidden id="token"&gt;Put an authentication token here&lt;/hidden&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>&nbsp;</p>
  
  <pre><code>//client.js
  $(function(){
      $('#login').click(function() {
          $.ajax({
              type: 'POST',
              url: 'http://localhost:9001/login',
              contentType: "application/json; charset=utf-8",
              datatype: 'json',
              success: function(result) {
                  console.log(result); // this is where I would consume/store the token
                  $('#login').html(':)');
              },
              error: function(result) {
                  console.log(status);
                  console.log(result);
              }
          });   
      });
  });
  </code></pre>