如何将数据从AngularJS前端传递到Nodejs后端?

时间:2016-02-29 12:04:26

标签: javascript html angularjs node.js

我这里有一些角度js代码。

<!DOCTYPE html>
<html lang="en">

  <head>
    <script src="Scripts/angular.min.js"></script>
        <body>    
      <div ng-app="">
        <form>
          Author:
          <input type="text" ng-model="author">
          <br>
          <br> Title:
          <input type="text" ng-model="title">
          <br>
          <br> Body:
          <input type="author" ng-model="body">
          <br>
          <br>
          <input type="submit" value="Submit">
        </form>
      </div>
    </head>
    </body>
</html>

和带有MySQL代码的节点js。我能够从这个节点代码传递数据到MySQL DB。如何继续使用角度到节点js?我来自PHP背景。我应该能够将角度js格式的数据发送到MySQL数据库。我可以从这里的节点代码向MySQL数据库发送数据。

var mysql = require('mysql');

var connection = mysql.createConnection({
  host: 'localhost',
  user: '',
  password: '',
  database: 'copedb'
});
connection.connect();
var cope = {
  author: 'XYZXYZ',
  title: 'Testing Node',
  body: 'Node JS'
};
var query = connection.query('insert into cope set ?', cope, function(err, result) {
  if (err) {
    console.error(err);
    return;
  }
  console.error(result);
});

4 个答案:

答案 0 :(得分:17)

它可以成为您入门的踏脚石:

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <script src="Scripts/angular.min.js"></script>
   <script src="Scripts/app.js"></script>
</head>
<body ng-app="myApp">    
  <div ng-controller="myCtrl">
    <form>
      Author:
      <input type="text" ng-model="author">
      <br>
      <br> Title:
      <input type="text" ng-model="title">
      <br>
      <br> Body:
      <input type="author" ng-model="body">
      <br>
      <br>
      <input type="submit" value="Submit" ng-click="submit()">
    </form>
  </div>
</body>

Angular code app.js

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   $scope.submit= function(){
      var data = $.param({
        book: JSON.stringify({
            author: $scope.author,
            title : $scope.title,
            body : $scope.body
        })
      });

      $http.post("/api/book/", data).success(function(data, status) {
        console.log('Data posted successfully');
      })
   }
});

server.js - Nodejs

var express = require('express'); 
var mysql = require('mysql');
var app = express();

var connection = mysql.createConnection({
     host: 'localhost',
     user: '',
     password: '',
     database: 'copedb'
});
connection.connect();

app.post('/api/book', function(req, res, next){
   var cope = req.body.params;
   var query = connection.query('insert into cope set ?', cope, function(err, result) {
     if (err) {
       console.error(err);
       return res.send(err);
     } else {
       return res.send('Ok');
     }
});
app.listen(8080);

答案 1 :(得分:3)

无论如何,我在这里写了实际的工作代码。

index.html

 <!DOCTYPE html>
 <html lang="en">
 <head>
 <script src="angular.min.js"></script>
 <script src="app.js"></script>
 </head>
 <body ng-app="myApp">
 <div ng-controller="myCtrl">
 <form>
    Author:
    <input type="text" ng-model="data.author">
    <br>
    <br> Title:
    <input type="text" ng-model="data.title">
    <br>
    <br> Body:
    <input type="author" ng-model="data.body">
    <br>
    <br>
    <input type="submit" value="Submit" ng-click="submit()">
  </form>
  </div>
  </body>
  </html>

app.js

 var app = angular.module('myApp', []);
 app.controller('myCtrl', function($scope,$http) {
 $scope.data = {};
$scope.submit= function(){
    console.log('clicked submit');
    $http({
        url: 'http://localhost:8080/blah',
        method: 'POST',
        data: $scope.data
    }).then(function (httpResponse) {
        console.log('response:', httpResponse);
    })
   }
 });

server.js

   var express = require('express');
   var bodyParser = require('body-parser');
   var mysql = require('mysql');
   var app = express();

    app.use(bodyParser.json({limit: '50mb'}));
    app.use(express.static('public'));

  var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'copedb'
   });
   connection.connect();

    app.post('/blah', function(req, res, next) {
    var cope = req.body;
    console.log('request received:', req.body);
   var query = connection.query('insert into cope set ?', cope, function (err,     result) {
    if (err) {
        console.error(err);
        return res.send(err);
    } else {
        return res.send('Ok');
    }
    });
    //res.send('received the data.');
    });
    app.listen(8080);

答案 2 :(得分:1)

首先,根据您的需求,使用 Express / Restify 创建一个REST服务,这些服务是npm模块,而这些需求将依次与您的SQL数据库通信。

一旦服务启动并在服务器级运行,您现在就可以在客户端级别向/从服务器发送/接收数据。

注意:使用 $ resource 代替AngularJS的 $ http 服务与服务器通信。

https://docs.angularjs.org/api/ngResource/service/ $资源

答案 3 :(得分:0)

如何将数据从AngularJS前端传递到Nodejs后端的最简单答案

带有html的AngularJs代码

 <body>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <div ng-app="app" ng-controller="myCtrl">
        <p>First Name: <input type="text" name="firstName" ng-model="firstName" required /></p>
        <p>Lirst Name: <input type="text" name="lastName" ng-model="lastName" required /></p>
        <button ng-click="SendData()">Submit</button>
        <hr />
        {{ PostDataResponse }}
    </div>
    <script>
        var app = angular.module("app",[]);
        app.controller("myCtrl", function($scope,$http){
        $scope.SendData = function() {
            var data = {
                    fName : $scope.firstName,lName : $scope.lastName
                }
            $http.post('/postFormAngular', data)
                .success(function (data, status, headers, config) {
                    $scope.PostDataResponse = data;
                })
                .error(function(data, status, header, config){
                    $scope.PostDataResponse = "Data: " + status;


                });
        };  
        });
    </script>
 </body>

Nodejs代码

var express = require('express');
var multer  =   require('multer');
var mime    =   require('mime');
var mysql = require('mysql');
var app = express();
var bodyParser =    require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  port      : 3306,
  password : '',
  database : 'angular_db'
});

connection.connect(function(err){
if(!err) {
    console.log("Database is connected ... nn");    
} else {
    console.log("Error connecting database ... nn");    
}
});

app.get('/angular_html.html', function(req, res){
    res.sendFile(__dirname + '/' + 'angular_html.html');
    console.log("----------------");
});
app.post("/postFormAngular", function (req, res) {
        console.log(req.body.fName);
        res.send(req.body.fName);
});
app.listen(3000);