这是我的网络服务,我将2个vars从app mobile发送到请求并回复json对象。
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.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 }]}));
});
// start the server
app.listen(port);
console.log('Server start! at http://localhost:' + port);
然后我想在我的angularjs控制器中获得那个json。 我不确定是否使用此表格
var app = angular.module('myApp',[]);
app.controller('vehicleCtrl', function($scope, $http) {
var url = "http://localhos:8080/coords";
$http.jsonp(url)
.success(function(data){
console.log(data.vehicle);
});
});
答案 0 :(得分:0)
我试图创建一个具有类似代码的示例。我为防止XOrigin问题所做的一件事是将index.html文件放在public
目录下面,该目录由server.js中的行app.use(express.static('public'));
提供。
<强>的index.html:强>
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="bower_components/angular/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);
});
}
}]);
</script>
</head>
<body>
<div ng-controller='demoCtrl'>
<h1>Test</h1>
<p><button ng-click="restart()">Restart</button></p>
</div>
</body>
</html>
<强> server.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.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: "foo", longitud: "bar" }]}));
});
// start the server
app.listen(port);
console.log('Server start! at http://localhost:' + port);