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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35699095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:08:03  来源:igfitidea点击:

How to pass data from AngularJS frontend to Nodejs backend?

javascripthtmlangularjsnode.js

提问by jeny

I have some angular js code here.

我这里有一些有角度的 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>

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.

和带有 MySQL 代码的节点 js 在这里。我能够从这个节点代码将数据传递到 MySQL DB。如何继续使用角度到节点 js?我来自 PHP 背景。我应该能够将数据从 angular 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);
});

回答by Mukesh Sharma

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

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

Index.html

索引.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

Angular 代码 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

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

回答by jeny

Anyways I have written actual working code here .

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

index.html

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

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

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

回答by Prajwal

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

首先,使用Express/Restify创建一个 RESTful 服务,这些服务是 npm 模块,根据您的需要依次与您的 SQL 数据库对话。

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 $resourceinstead of $httpservice of AngularJS for talking to the server.

注意:使用$resource而不是AngularJS的$http服务与服务器通信。

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

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

回答by Rijo

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

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

AngularJs code with html

带有 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 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);