将json从Angular JS传递给Node JS

时间:2016-11-24 09:36:53

标签: javascript angularjs json node.js express

我正在尝试将我的前端(Angular)和后端(Node)结合起来,但有些前端没有将json传递给后端

这是我的Angular-js

的html代码

的index.html

<html>
<head>Testing
<script src = "angular.min.js" ></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
   $scope.submit= function(){
      var data = $.param({
        book: JSON.stringify({
            author: $scope.author,
            title : $scope.title,
            body : $scope.body
        })
      });
    console.log(data)
      $http.post("/", data).success(function(data, status) {
        console.log('Data posted successfully');
      })
   }
});
</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>
</html>

我的节点应用程序如下所示。

Server.js

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.urlencoded({ extended: true })); 
app.use(bodyParser.json());

app.get('/', function(req, res){
  res.sendFile(__dirname +'/index.html');
});

app.post('/', function(req,res,next){
    console.log(req.body)   
    res.status(200).send('Ok')
})

console.log('server running at 3000!')
app.listen(3000);

我在浏览器的'/'路线上获得了Index.html,但是当我提交时没有发生任何事情。

提前致谢

1 个答案:

答案 0 :(得分:2)

你能试试吗

var data = {
  book: {            
    author: $scope.author,
    title : $scope.title,
    body : $scope.body
  }
}

$http.post("/", data).success(function(data, status) {
    console.log('Data posted successfully');
})