将快速js数据发布到角度js

时间:2015-12-09 21:28:41

标签: angularjs json node.js web-services express

我想在我的视图index.html中获取vars lat和lon,但是我的Web服务中的对象工具总是空的。 这是script.js:

var express = require('express');
    var app = express();
    var port = process.env.PORT || 8080;
    var bodyParser = require('body-parser');
    app.use(bodyParser.json()); // support json encoded bodies
    app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
    app.use(express.static('public'));
    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });

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

    app.post('/coords', function(req, res) {

        var lat         = req.body.lat,
            lon         = req.body.lon;

        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({"vehicle": [{ "latitud": lat, "longitud": lon }]}));

    });

    app.listen(port);
    console.log('Server start! at http://localhost:' + port);

这是我的观点index.html

<!DOCTYPE html>
<html lang="es" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var app = angular.module('myApp',[]);
        app.controller('demoCtrl', ['$scope', '$http', function($scope, $http) {
            $scope.restart =function(){
                console.log('Restart');
                var url = 'http://localhost:8080/coords';
                $http.post(url)
                    .success(function(data){
                        console.log(data.vehicle);
                        $scope.datos = data.vehicle;
                    });
            }
        }]);

    </script>
</head>
<body>
<div  ng-controller='demoCtrl'>
    <h1>Test Sinarr</h1>
    <p><button ng-click="restart()">mostrar</button></p>
    <h2 ng-repeat="lat in datos">Latitud: {{lat.latitud}}</h2>
    <h2 ng-repeat="lon in datos">Longitud: {{lon.longitud}}</h2>
</div>
</body>
</html>

当我打电话给网络服务时,我发送了2个帖子坐标,然后在浏览器中我希望在我的视图index.html中打印那些坐标,但总是我按下对象json为空的按钮。有什么建议??

0 个答案:

没有答案