mysql - 使用 NodeJS 从 MySQL 数据库中检索数据并将其传递给 AngularJS 页面

标签 mysql angularjs node.js

我已经搜索并搜索了一个明确的答案,但似乎找不到。 我是编程的“新手”,至少在涉及 AngularJS 和 NodeJS 时(我在学校熟悉的基本语言,如 HTML、CSS 和纯 JS)。

我希望能够使用 NodeJS 从 MySQL 数据库获取数据,然后将该数据发送到包含 AngularJS 的 HTML 页面。

在我想创建此连接之前,我首先使用 AngularJS 直接从 $scope 检索数据,并能够将其与 html 上的下拉列表绑定(bind)。不错

然后,在 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

最佳答案

所以你想学习如何使用 AngularJS、NodeJS 和 MySQL。很不错。 AngularJS 和 NodeJS 都使用 JavaScript。 AngularJS 是 100% 的 JavaScript。只有少数螺母和 bolt 必须装配在一起。 AngularJS 专注于前端,而 NodeJS 专注于后端。 MySQL用于数据库管理。只有少数技巧是您必须使用的,例如 MVC 才能使您的代码工作并变得健壮。您可以通过多种方式实现您的项目。其中之一如下:

  1. 启动 Node.js 命令提示符。
  2. 创建新的项目目录。例如“myjspro”
  3. cd pathto/myjspro 或 cd pathto\myjspro 或 cd pathto\myjspro
  4. npm 初始化
  5. npm install mysql --save
  6. npm install express --save
  7. npm install body-parser --save
  8. 等等

完成上述步骤后,我们就可以开始编码了。在您的后端代码中,您需要设置监听端口。您还需要配置默认目录。在您的前端,您可以使用数据绑定(bind)将您的数据模型连接到您的 View 。例如范围是应用程序 Controller 和 View 之间的粘合剂。以模块化方式构建您的应用程序。我们可以为我们的应用程序使用许多构建 block 。列表是无止境的,所以让我们开始吧……双 curl 表达式 {{ }} 用于观察、注册监听器方法和更新 View 。

前端:

  • app/view/index.html
  • 应用程序/js/app.js
  • 应用程序/js/test.js
  • 应用程序/lib/angular/angular.js
  • 应用程序/lib/jquery/jquery.js

后端:

  • db/mydb2.sql

  • Node 模块

  • index.js

  • package.json

数据库:

  • 创建数据库,例如“mydb2”
  • 创建数据库用户,例如“jspro2”
  • 创建数据库用户的密码。
  • 为项目创建数据库表,例如“客户2”

要启动您的项目,您可以在命令提示符下使用:node index.jsnpm start。该应用程序将在本地主机上运行。使用浏览器查看项目。即 http://localhost:8000/

快乐编码...


index.js

//////////////////////
//
// index.js
//
///////////////////////

console.log("Start...");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var now = new Date();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname+'/app'));

var conexao = mysql.createConnection({
    host: "localhost",
    user: "jspro2",
    password: "jspro32",
    database: "mydb2"
});

conexao.connect(function(err){
    if(err){
        console.log(info()+" "+err);
    }
    else
    {
        console.log(info()+" connected...");
    }
});

function info()
{
    now = new Date();
    return now.getTime();
}

app.set('port', (process.env.PORT || 8000));
app.get('/', function(req, res){
    console.log(info()+" page request.... ");
    res.sendFile(__dirname +'/'+'app/view/index.html');
});

app.get('/clientes', function(req, res){
    console.log(info()+" clientes request.... ");
    var sql = "SELECT * FROM CLIENTES2";
    conexao.query(sql, function(err, result, fields){
        if(err){
            console.log(info()+" "+err);
            res.send(info()+": dbErr...");
        }
        else
        {
            console.log(info()+" "+result);
            res.send(result);
        }
    });
});

app.post('/clientPost', function(req, res){
    var data = req.body;
    var dnome = data.nome;
    var dmorada = data.morada;
    var sql = "INSERT INTO CLIENTES2 (nome,morada) VALUES(?, ?)";
    conexao.query(sql, [dnome, dmorada], function(err, result){
        if(err){
            console.log(info()+":02 "+err);
            res.send(info()+": dbErr02...");
        }
        else
        {
            console.log(info()+" "+ result);
            res.send(result);
        }
    });
});

var dport = app.get('port');
app.listen(dport, function(){
    console.log(info()+" "+" app is running at http://localhost:"+dport+"/");
    console.log("   Hit CRTL-C to stop the node server.  ");
});
//   
//

app.js

/////////////////////////
//
// app.js
//
/////////////////////////////////

//alert("start...");
var now = new Date();

//Define the clientesApp module.
var clientesApp = angular.module('clientesApp', []);

//Define the clientesCtrl controller.
clientesApp.controller('clientesCtrl', function clientsList($scope, $http){
    $scope.clientes = [
        {
            nome: 'Marc',
            morada: '123 West Parade, Nome'
        },
        {
            nome: 'Jean',
            morada: '432 East Cresent, Lisboa'
        }
    ];

    $scope.feedback = now;

    $scope.listView = function(){
        //alert("View");
        $http.get('/clientes').then(function(data){
            $scope.clientes = data.data;
            $scope.feedback = data;
        }); 
    };

    $scope.listSubmit = function(){
        //alert("Submit..");
        var listData = {
            nome: $scope.nome,
            morada: $scope.morada
        };
        //alert(listData.nome);
        $http.post('/clientPost', listData).then(function(data){
            $scope.feedback = data;
        }); 
    };

});

//alert(now);
//
//

index.html

<!DOCTYPE html>
<!--
index.html
-->
<html lang="en">
    <head>
        <title>DemoJSPro</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body ng-app="clientesApp">
        <h1>AngularJS Demo using NodeJS and MySQL.</h1>

        <div ng-controller="clientesCtrl">
            <hr>
            <div>{{ feedback }}</div>
            <hr>
            <div>
                <br>
                Nome:
                <input type="text" ng-model="nome">
                <br>
                Morada:
                <input type="text" ng-model="morada">
                <br>
                <input type="button" value="OK" ng-click="listSubmit()">
                <br>
            </div>
            <div>
                <p>Selecionar um registo:</p>
                <select ng-model="clienteSelecionado" ng-options="x.nome for x in clientes"> 
                </select>
                <table>
                    <tr>
                        <td>{{ clienteSelecionado.nome }}</td>
                        <td>{{ clienteSelecionado.morada }}</td>
                    </tr>
                </table>
            </div>
            <hr>
            <div>
                <input type="button" value="View" ng-click="listView()">
                <hr>
                <table>
                    <tr>
                        <th>###</th>
                        <th>Nome</th>
                        <th>Morada</th>
                    </tr>
                    <tr ng-repeat=" y in clientes">
                        <td>{{ $index + 1 }}</td>
                        <td>{{ y.nome }}</td>
                        <td>{{ y.morada }}</td>
                    </tr>
                </table>
            </div>
            <br>
            <hr>
            <br><br>
        </div>

        <script src="../lib/angular/angular.js"></script>
        <script src="../lib/jquery/jquery.js"></script>
        <script src="../js/app.js"></script>
        <script src="../js/test.js"></script>
    </body>
</html>

mydb2.sql

#//////////////////////////
#//
#// mydb2.sql
#//
#///////////////////////////

CREATE DATABASE MYDB2;

USE MYDB2;

CREATE TABLE CLIENTES2 (
id int NOT NULL auto_increment,
nome varchar (30) NOT NULL,
morada varchar (99) NOT NULL,
PRIMARY KEY (id)
);

GRANT ALL ON MYDB2.* to jspro2@localhost identified by 'jspro32';

享受吧。


关于mysql - 使用 NodeJS 从 MySQL 数据库中检索数据并将其传递给 AngularJS 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52276297/

相关文章:

javascript - AngularJS 将模型链接到 ng-show

javascript - Edge 浏览器 - iframe.document.open 不起作用

node.js - 模拟 Typeorm QueryBuilder

php - 无法使用 phpseclib 在 MySQL 中运行 SQL 查询

java - 我如何在 Grails 中生成数据库表?

javascript - Angular Service 创建的函数需要 this 关键字

node.js - AWS Lambdas 的本地开发服务器

node.js - 使用 nodemailer 发送邮件 - 来自字段的电子邮件不正确

Mysql 查询 rand() 并排序

mysql - 按日期时间字段准确分页