How to pass data from AngularJS frontend to Nodejs backend?

前端 未结 4 1882
滥情空心
滥情空心 2020-12-04 18:29

I have some angular js code here.




  
    

        
相关标签:
4条回答
  • 2020-12-04 19:02

    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);
    
    0 讨论(0)
  • 2020-12-04 19:06

    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);
    
    0 讨论(0)
  • 2020-12-04 19:10

    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);
    
    0 讨论(0)
  • 2020-12-04 19:11

    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

    0 讨论(0)
提交回复
热议问题