【问题标题】:Retrieving data from MySQL database using NodeJS and passing it to AngularJS page使用 NodeJS 从 MySQL 数据库中检索数据并将其传递给 AngularJS 页面
【发布时间】: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

【问题讨论】:

    标签: mysql angularjs node.js


    【解决方案1】:

    所以你想学习如何使用 AngularJS、NodeJS 和 MySQL。很不错。 AngularJS 和 NodeJS 都使用 JavaScript。 AngularJS 是 100% 的 JavaScript。只有几个螺母和螺栓必须装配在一起。 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

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

    前端:

    • app/view/index.html
    • app/js/app.js
    • app/js/test.js
    • app/lib/angular/angular.js
    • app/lib/jquery/jquery.js

    后端:

    • db/mydb2.sql

    • node_modules

    • 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';
    

    享受吧。


    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 2013-12-05
      • 2015-06-24
      • 2017-11-26
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 2014-09-30
      相关资源
      最近更新 更多