Angular js不会从节点js获得json响应

时间:2015-08-03 07:31:10

标签: javascript json angularjs node.js express

我正在尝试在节点(中间件)和角度(UI)之间建立REST连接。但是,json显示在浏览器上,而不是通过angular controller / html

进行路由

Node / Express router.js

router.get('/members', function(request, response){
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "GET, POST");
response.setHeader('Content-Type', 'application/json');
var dbdata = [];
var str;
db.get('_design/views555/_view/app_walltime', function (err, body) {
    if (!err) {         
        body.rows.forEach(function(doc) {
            dbdata.push({name: doc.key, walltime:doc.value});
        });
        console.log(dbdata);
        response.json(dbdata);

Angular controllers.js

'use strict';
var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.config(['$httpProvider', function($httpProvider, $routeProvider, $locationProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);


phonecatApp.controller('PhoneListCtrl', function ($scope, $http, $templateCache) {
  alert('asdsad');
  $scope.list = function() {
  alert('hereh');
  var url = 'http://192.168.59.103:8072/members';// URL where the Node.js server is running 

 $http.get(url).success(function(data) {
      alert(data);
      $scope.phones = data; 

  });
  };
  $scope.list();
});

html - testangular.js

<html ng-app="phonecatApp">
<head>
<meta charset="utf-8">
<title>My HTML File</title>
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css">
<script src="/bower_components/angular/angular.js"></script>
<script src="/bower_components/angular-route/angular-route.min.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-controller="PhoneListCtrl">
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
  <ul class="phones">
    <li ng-repeat="phone in phones | filter:query">
      {{phone.name}}
      <!--<p>{{phone.walltime}}</p> -->
    </li>
  </ul>
</div>
</div></div>

浏览器上的内容如下所示

[{ “名称”: “APP1”, “walltime”: “1050”},{ “名称”: “APP2”, “walltime”: “30”}]

我似乎缺少一些让节点和角度通信的配置。请让我知道我做错了什么。

2 个答案:

答案 0 :(得分:1)

您在浏览器窗口中看到的是JSON对象,这是您请求的结果。

使用行$scope.phones = data;,您只需将$scope对象分配给Angular data,而无需实际解析它。 结果是Angular无法在ng-repeat指令中理解实际上{{phone.name}}{{phone.walltime}}是什么,并且显示了JSON字符串。

为了使ng-repeat指令按预期工作,您必须首先解析JSON对象,处理它(例如创建自定义对象并分配其属性),然后将其分配给{{1}对象。

您可以使用类似的方式执行解析 $scope。 有关详细信息,请查看this question

甚至使用Angular的内置函数angular.fromJson(data)

可以这样做一个例子:

JSON.parse(data);

答案 1 :(得分:0)

测试一下:

webroot/assets/*