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

我这里有一些有角度的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代码的node js。我能够从此节点代码将数据传递到MySQL DB。如何继续对Node

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

});

回答:

它可能是您入门的垫脚石:

回答:

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

回答:

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

})

}

});

回答:

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

以上是 如何将数据从AngularJS前端传递到Nodejs后端? 的全部内容, 来源链接: utcz.com/qa/406679.html

回到顶部