【发布时间】:2019-02-15 23:32:03
【问题描述】:
我已经搜索并搜索了一个明确的答案,但似乎找不到。 我是编程的“新手”,至少是关于 AngularJS 和 NodeJS(HTML、CSS 和普通 JS 等基础语言,因为学校我很熟悉)。
我希望能够使用 NodeJS 从 MySQL 数据库中获取数据,然后将该数据发送到包含 AngularJS 的 HTML 页面。
在我想创建这个连接之前,我首先使用 AngularJS 直接从 $scope 检索数据,并能够将它与 html 上的下拉列表绑定。不错
然后,在 NodeJS 中,我连接到 MySQL 数据库(这里在 Workbench 上运行),并能够从表中检索数据并将其显示在控制台上。很不错。
但是 AngularJS 请求 NodeJS 从 MySQL 获取数据并将其发送回 AngularJS 怎么样?这是我做不到的:(
AngularJS 代码:
<!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 代码:
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();
});
给你。我希望有人能指出我正确的方向。 非常感谢,编码愉快! :D
【问题讨论】: