web-dev-qa-db-fra.com

Comment passer des données du frontend AngularJS au backend Nodejs?

J'ai du code angular js ici.

<!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>

et le noeud js avec le code MySQL ici. Je peux transmettre des données à MySQL DB à partir de ce code de nœud. Comment aller de l'avant avec angular to node js? I come from a PHP background. I should be able to send data from angular js form à la base de données MySQL. Je peux envoyer des données à la base de données MySQL à partir du code de nœud ici.

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);
});
10
jeny

Cela peut être le tremplin pour commencer:

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>

Code angulaire 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);
18
Mukesh Sharma

Quoi qu'il en soit, j'ai écrit le code de travail réel ici.

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);
3
jeny

Tout d'abord, créez un service RESTful en utilisant Express/Restify qui sont des modules npm, en fonction de vos besoins qui, à leur tour, parleront à votre base de données SQL.

Une fois que le service est opérationnel au niveau du serveur, vous êtes maintenant prêt à envoyer/recevoir des données vers/depuis le serveur au niveau du client.

Remarque: utilisez $ resource au lieu de $ http service AngularJS pour parler au serveur.

https://docs.angularjs.org/api/ngResource/service/ $ ressource

1
Prajwal

Réponse la plus simple pour savoir comment transmettre des données du frontend AngularJS au backend Nodejs

Code AngularJs avec html

 <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>

Code 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);
0
Rijo