I've searched and searched for a clear answer but can't seem to find it. I'm "new" to programming, at least when it's about AngularJS and NodeJS (base languages like HTML, CSS and plain JS I'm familiar with because of school).
I want to be able to get data from a MySQL database using NodeJS and then send that data to an HTML page that has AngularJS in it.
Before I wanted to create this connection, I first used AngularJS to retrieve data directly from $scope and was able to bind it with a dropdown on html. Nice
Then, in NodeJS I made a connection to a MySQL database (here running on Workbench) and was able to retrieve data from a table and display it on console. Very nice.
But how about AngularJS request NodeJS to get data from MySQL and send it back to AngularJS? This I can't do :(
AngularJS code:
<!DOCTYPE html>
<html>
<head>
<title>HumbleMoney</title>
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> // AngularJS file
</head>
<body ng-app="clientesApp" ng-controller="clientesCtrl"> // Start App and Controller
<p>Selecionar um registo:</p>
<select ng-model="clienteSelecionado" ng-options="x.nome for x in clientes"></select> // dropdown that should get the "nome" value of each record in $scope.clientes
<table> // table with 2 columns that get the "nome" and "morada" values from the selected item on the above dropdown
<tr>
<td>{{clienteSelecionado.nome}}</td>
<td>{{clienteSelecionado.morada}}</td>
</tr>
</table>
<script>
var app = angular.module('clientesApp', []);
app.controller('clientesCtrl', function($scope, $http) {
$http.get('NodeJS/clientes.js') //make a GET request on the NodeJS file
.then(function(data) {
$scope.clientes = data; //make the $scope.clientes variable have the data retrieved, right?
})
});
</script>
</script>
</body>
</html>
NodeJS code:
var express = require('express');
var app = express();
app.get('/', function (req, res){ //is this how you handle GET requests to this file?
var mysql = require('mysql'); //MySQL connection info
var conexao = mysql.createConnection({
host:"localhost",
user:"root",
password:"",
database:"mydb"
});
conexao.connect(function(erro) { //MySQL connection
if (erro) {
res.send({erro})
} else {
var sql = "SELECT nome, morada FROM clientes";
conexao.query(sql, function(erro, data) {
if (erro) {
res.send({erro})
} else {
res.send({data}); //this should bind the result from the MySQL query into "res" and send it back to the requester, right?
}
});
}
});
conexao.end();
});
Here you have it. I hope someone could point me in the right direction. Thank's a lot and happy coding! :D