在我的应用程序中声明控制器并将其链接在一起时遇到问题
Trouble declaring and linking a controller together in my app
所以我有 3 个文件。有一个源文件夹,其中包含我的 app.js 文件,还包含名为 Sheets_API_Quickstart 的文件夹,其中包含 quickstart.js,还有一个名为 Project 的文件夹,其中包含 Waiting_List.html
我试图设置我的控制器,以便我可以使用按钮从 Waiting_List.html 调用函数 test()。不幸的是,我的应用程序在尝试实现后甚至无法启动。它给出了控制台错误 Failed to load resource: net::ERR_CONNECTION_REFUSED
是否有明显我遗漏或做错的事情?
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>
您混淆了前端和后端。 Node.js 是服务器端语言,angular 是客户端语言。当它们一起工作时,您通常不会从同一个脚本中管理它们。我想你会想做一个完整的 MEAN stack tutorial 来解决其中的一些问题。
所以我有 3 个文件。有一个源文件夹,其中包含我的 app.js 文件,还包含名为 Sheets_API_Quickstart 的文件夹,其中包含 quickstart.js,还有一个名为 Project 的文件夹,其中包含 Waiting_List.html
我试图设置我的控制器,以便我可以使用按钮从 Waiting_List.html 调用函数 test()。不幸的是,我的应用程序在尝试实现后甚至无法启动。它给出了控制台错误 Failed to load resource: net::ERR_CONNECTION_REFUSED
是否有明显我遗漏或做错的事情?
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>
您混淆了前端和后端。 Node.js 是服务器端语言,angular 是客户端语言。当它们一起工作时,您通常不会从同一个脚本中管理它们。我想你会想做一个完整的 MEAN stack tutorial 来解决其中的一些问题。