0

Link to Github

So I have 3 files. There is a source folder which contains my app.js file and also contains folder called Sheets_API_Quickstart, which contains quickstart.js, and a folder called Project, which contains Waiting_List.html

I attempted to set up my controller so I could call a function test() from Waiting_List.html using a button. Unfortunately my app won't even start after trying to implement this. It gives a console error Failed to load resource: net::ERR_CONNECTION_REFUSED

Is there something really obvious that I'm missing or doing wrong?

app.js

var express = require('express');
var app = express();
var fs = require('fs');
var myApp = angular.module('myApp.controllers', []);
//var file = "DaycareDB.db";
//var exists = fs.existsSync(file);
//var db = OpenDatabase(file);

app.use(express.static(__dirname + '/Project'));

app.use(express.static(__dirname + '/'));


app.get('/', function (req, res) {
    res.sendFile('Project/Home.html', {root: __dirname });
});


app.listen(3000);
console.log("running at port 3000");

quickstart.js

angular.module('myApp.controllers').controller('QuickstartController', ['$scope', '$http', function($scope, $http){


var fs = require('fs');
var updateDB = require('./updateDB.js');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var splitData;


// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
var array = [];

var test = function(){
  console.log("Hello World");
}

var run = {
  runQuickstart : function() {
    // Load client secrets from a local file.
    fs.readFile('client_secret.json', function processClientSecrets(err, content) {
      if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
      }
      // Authorize a client with the loaded credentials, then call the
      // Google Sheets API.
      authorize(JSON.parse(content), listChildren);
    });
  },

  test : function(){
    console.log("Hello World");
  }
}

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var auth = new googleAuth();
  var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } 
    else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } 
  catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

/**
 * Print the information for children to be registered, store that information in the database.
 */
function listChildren(auth) {
  var sheets = google.sheets('v4');
  sheets.spreadsheets.values.get({
    auth: auth,
    spreadsheetId: '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI', //this can be found in the URL of our google sheet
    range: 'Form Responses 1!A2:X2',
  }, function(err, response) {
      if (err) {
        console.log('The API returned an error: ' + err);
        return;
      }
      var rows = response.values;
      if (!rows) {
        console.log('No data found.');
        return;
      } 
      else {
        updateDB.inputFormToDB.apply(this, rows);
        console.log('Form Responses');
        for (var i = 0; i < rows.length; i++) {
          var row = rows[i];
          // Print columns A through X, which correspond to indices 0 through 23.
          console.log('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s', row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9],row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17], row[18], row[19], row[20], row[21], row[22], row[23]);
        }
        var spreadsheetId = '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI'; //this can be found in the URL of our google sheet
        var requests = [];
        requests.push({
          "deleteDimension": {
            "range": {
              "sheetId": 1484177643, //this can be found after the string 'gid=' in the URL of our google sheet
              "dimension": "ROWS",
              "startIndex": 1,
              "endIndex": 2
            }
          }
        });
        requests.push({
          "insertDimension": {
            "range": {
              "sheetId": 1484177643, //this can be found after the string 'gid=' in the URL of our google sheet
              "dimension": "ROWS",
              "startIndex": 499,
              "endIndex": 500
            }
          }
        });
        var batchUpdateRequest = {requests: requests}
        sheets.spreadsheets.batchUpdate({
          auth: auth,
          spreadsheetId: spreadsheetId, //this can be found in the URL of our google sheet
          resource: batchUpdateRequest
        }, function(err, response) {
            if(err) {
              // Handle error
              console.log(err);
            }
            else{
              sheets.spreadsheets.values.get({
                auth: auth,
                spreadsheetId: '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI', //this can be found in the URL of our google sheet
                range: 'Form Responses 1!A2',
              }, function(err, response) {
                  if (err) {
                    console.log('The API returned an error: ' + err);
                    return;
                  }
                  var cell = response.values;
                  if (!cell) {
                    console.log('SHEET IS EMPTY NOW.');
                    return;
                  } 
                  else {
                    setTimeout(function() { listChildren(auth); },1150);
                  }
              });
            }
        });
      }
  });
}

module.exports = run;

}]);

Waiting_List.html

<DOCTYPE! html>
<html>


<head>

<script type="text/javascript" src="WaitingList.js"></script>
<style type="text/css">
.TFtable {
    width:100%;
    border: 1px solid black;
    background-color: black;
/*  border-collapse: collapse; */
    padding: 5px;
}
/*  Define the background color for all the ODD background rows  */
    .TFtable tr:nth-child(odd){ 
        background: #b8d1f3;
    }
    /*  Define the background color for all the EVEN background rows  */
    .TFtable tr:nth-child(even){
        background: #dae5f4;
    }
</style>
<script type="text/javascript" src="updateDB.js"></script>
<script type="text/javascript" src="quickstart.js"></script>
<script src="app.js"></script>
<script src="quickstart.js"></script>

</head>
<body ng-app="myApp" ng-controller="QuickstartController">

<h1>Waiting List Testing</h1>

<button type="button" onclick="()" ng-submit="test()">Refresh List</button>
<div id="display"></div>

<table class = "TFtable">
    <tr>
    <th>Child's Name</th>
    <th>D.O.B.</th>
    <th>Phone Number</th>
    <th>Primany Parent Name</th>
    <th>Primanry Parent Status</th>
    <th>Secondary Parent Name</th>
    <th>Secondary Parent Status</th>
    <th>Date of App.</th>
    <th>Desired Start Date</th>
    <th>Class</th>
    <th>Days</th>
    <th>View Profile</th>
    <th>Accept</th>
</tr>
<tr>
    <th>Jessica Brown</th>
    <th>06/04/2007</th>
        <th>(123)456-7890</th>
        <th>John Brown</th>
        <th>Student</th>
        <th>Jane Brown</th>
        <th>Comunaty</th>
        <th>10/31/2016</th>
        <th>1/1/2017</th>
        <th>IN</th>
        <th>MWF</th>
<!-- make shure all button code is between the <th> and </th> tags -->
        <th><button type="button" onclick="profile()"> Profile</button></th>
        <th><button type="button" onclick="accept()">Accept</button> </th>

</table>

<p id="accepted"></p>

<script>

function accept(){
    confirm("You clicked accept! \nNothing has happened.\n Thank you.");
}

function profile(){
    window.location.href = 'DemoPage.html';
}

</script>


</body>
</html>
Ryan
  • 262
  • 3
  • 19

1 Answers1

2

You are mixing up front-end and back-end. Node.js is a server side language, and angular is client side. While they work together, you usually don't manage them from the same script. I think you'll want to do a full MEAN stack tutorial to untangle some of this.

Larry Turtis
  • 1,907
  • 13
  • 26
  • Ah. I'll take a look at that. But basically what you're saying is that I have to have a .js file for a controller with a function who's purpose is to send a command to an endpoint service that'll send that command to the server and then I can catch it back there and then use that to run the function I'm trying to run in quickstart.js? That's how we did things for an app at my last job.. I'm just not sure how to set all that up. – Ryan Nov 05 '16 at 18:32