Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from AngularJS frontend to Nodejs backend?

I have some angular js code here.

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

and node js with MySQL code here. I am able to pass data to MySQL DB from this node code. How to go ahead with angular to node js? I am coming from a PHP background. I should be able to send data from angular js form to MySQL database. I am able to send data to MySQL database from node code here.

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);
});
like image 215
jeny Avatar asked Feb 29 '16 12:02

jeny


4 Answers

It can be the stepping stone for you to getting started:

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);
like image 197
Mukesh Sharma Avatar answered Nov 06 '22 11:11

Mukesh Sharma


First of all, create a RESTful service using Express/Restify which are npm modules, based on your needs which will in turn talk to your SQL database.

Once the service is up and running at the server-level, you are now ready to send/receive data to/from the server at the client-level.

Note: Make use of $resource instead of $http service of AngularJS for talking to the server.

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

like image 36
Prajwal Avatar answered Nov 06 '22 10:11

Prajwal


Anyways I have written actual working code here .

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);
like image 29
jeny Avatar answered Nov 06 '22 12:11

jeny


Easiest Answer for How to pass data from AngularJS frontend to Nodejs backend

AngularJs code with 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>

Nodejs code

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);
like image 21
Rijo Avatar answered Nov 06 '22 10:11

Rijo